哪位大神能告诉我怎么用 java 封装 get 和 post 请求

本贴最后更新于 1575 天前,其中的信息可能已经时移俗易

哪位大神能告诉我怎么用java封装get和post请求

8 回帖
请输入回帖内容 ...
  • zifeng

    😁 都是Happy大佬教出来的好学生

  • 其他回帖
  • huahua

    这个给力,就是格式有点乱,我帮你调整下。

  • Carrie
    *********************************************POST******************************************************
    
    public static String doPost(String url,Map<String, String> params) {
    		HttpPost httpPost = new HttpPost(url);
    //		取出map中所有的参数名
    		Set<String> keys = params.keySet();
    		String result ="";
    		List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    //		通过循环将参数保存到lst集合
    		for(String name:keys) {
    			String value = params.get(name);
    			parameters.add(new BasicNameValuePair(name, value));
    		}
    		try {
    			httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
    //			准备请求头数据
    			HttpClient httpClient = HttpClients.createDefault();			//创建客户端
    			HttpResponse httpResponse = httpClient.execute(httpPost);	//发送请求
    //			发起请求,获取接口响应信息
    			result = EntityUtils.toString(httpResponse.getEntity());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return result;
    	}
    	
    
  • Carrie
    /**以get的方法处理接口请求调用
    	 * @param url
    	 * @param params
    	 * @return
    	 */
    	public static String doGet(String url,Map<String, String> params) {
    		List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    //		取出所有参数
    		Set<String> keys = params.keySet();
    //		通过循环将参数保存到lst集合
    		for(String name:keys) {
    			String value = params.get(name);
    			parameters.add(new BasicNameValuePair(name, value));
    		}
    		String parameter = URLEncodedUtils.format(parameters, "UTF-8");
    		url+="?"+ parameter;
    		HttpGet httpGet = new HttpGet(url);
    		HttpClient httpClient = HttpClients.createDefault();
    		String result ="";
    		try {
    			HttpResponse httpResponse = httpClient.execute(httpGet);
    			result =EntityUtils.toString(httpResponse.getEntity());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return result;
    		}
    
  • 查看更多回帖