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

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

8 回帖
请输入回帖内容 ...
  • 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;
    		}
    
  • 其他回帖
  • 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;
    	}
    	
    
  • huahua

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

  • huahua

    Java 是世界上最优美的语言吗?这么说,会不会被打

  • 查看更多回帖