使用 HttpClient 调用接口详解编程语言

 
public class ClientUtils { 
 
	/** 
    * POST             请求 
    * @param url       请求地址 
    * @param params    请求参数 
    * @param encode    编码格式 
    * @return 
    * @throws ClientProtocolException 
    * @throws IOException 
    */ 
   public JSONObject doPostMethod(String url,Map<String,String> params,String encode) throws ClientProtocolException, IOException{ 
       HttpClient httpclient = HttpClients.createDefault(); 
       HttpPost httpPost = new HttpPost(url); 
       if (params != null) { 
           List<NameValuePair> form = new ArrayList<NameValuePair>(); 
           for (String name : params.keySet()) { 
               form.add(new BasicNameValuePair(name,params.get(name))); 
           } 
           UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,encode); 
           httpPost.setEntity(entity); 
       } 
       HttpResponse response = httpclient.execute(httpPost); 
       String result = EntityUtils.toString(response.getEntity()); 
       JSONObject obj = JSONObject.parseObject(result); 
       return obj; 
   } 
    
   /** 
    * GET 
    * @param url 
    * @param params 
    * @param encode 
    * @return 
    * @throws ClientProtocolException 
    * @throws IOException 
    */ 
   public JSONObject doGetMethod(String url,List<NameValuePair> params,String encode) throws ClientProtocolException, IOException{ 
	   HttpClient httpclient = HttpClients.createDefault(); 
	 //参数转换为字符串 
       String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params, encode)); 
       url = url + "?" + paramsStr; 
       // 创建httpget. 
       HttpGet httpget = new HttpGet(url); 
       System.out.println("executing request " + httpget.getURI()); 
       HttpResponse response = httpclient.execute(httpget); 
       String result = EntityUtils.toString(response.getEntity()); 
       JSONObject obj = JSONObject.parseObject(result); 
	   return obj; 
   } 
    
}

 

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/17484.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论