IT虾米网

使用 HttpClient 调用接口详解

shasha 2020年09月12日 编程语言 162 0
 
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; 
   } 
    
}

 

 

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

【linux】find删除指定时间之前的文件详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。