java使用httpclient封装post请求和get的请求

在我们程序员生涯中,经常要复用代码,所以我们应该养成时常整理代码的好习惯,以下是我之前封装的httpclient的post和get请求所用的代码:


[java]  view plain  copy
  1. package com.marco.common;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.net.URI;  
  7. import java.util.ArrayList;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import org.apache.http.HttpEntity;  
  13. import org.apache.http.HttpResponse;  
  14. import org.apache.http.HttpStatus;  
  15. import org.apache.http.NameValuePair;  
  16. import org.apache.http.StatusLine;  
  17. import org.apache.http.client.HttpClient;  
  18. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  19. import org.apache.http.client.methods.CloseableHttpResponse;  
  20. import org.apache.http.client.methods.HttpGet;  
  21. import org.apache.http.client.methods.HttpPost;  
  22. import org.apache.http.entity.StringEntity;  
  23. import org.apache.http.impl.client.CloseableHttpClient;  
  24. import org.apache.http.impl.client.DefaultHttpClient;  
  25. import org.apache.http.impl.client.HttpClients;  
  26. import org.apache.http.message.BasicNameValuePair;  
  27. import org.apache.http.protocol.HTTP;  
  28. import org.apache.http.util.EntityUtils;  
  29. import org.apache.log4j.Logger;  
  30.   
  31. /** 
  32.  * @author 马弦 
  33.  * @date 2017年10月23日 下午2:49 
  34.  * HttpClient工具类 
  35.  */  
  36. public class HttpUtil {  
  37.       
  38.     private static Logger logger = Logger.getLogger(HttpUtil.class);  
  39.   
  40.     /** 
  41.      * get请求 
  42.      * @return 
  43.      */  
  44.     public static String doGet(String url) {  
  45.         try {  
  46.             HttpClient client = new DefaultHttpClient();  
  47.             //发送get请求  
  48.             HttpGet request = new HttpGet(url);  
  49.             HttpResponse response = client.execute(request);  
  50.    
  51.             /**请求发送成功,并得到响应**/  
  52.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  53.                 /**读取服务器返回过来的json字符串数据**/  
  54.                 String strResult = EntityUtils.toString(response.getEntity());  
  55.                   
  56.                 return strResult;  
  57.             }  
  58.         }   
  59.         catch (IOException e) {  
  60.             e.printStackTrace();  
  61.         }  
  62.           
  63.         return null;  
  64.     }  
  65.       
  66.     /** 
  67.      * post请求(用于key-value格式的参数) 
  68.      * @param url 
  69.      * @param params 
  70.      * @return 
  71.      */  
  72.     public static String doPost(String url, Map params){  
  73.           
  74.         BufferedReader in = null;    
  75.         try {    
  76.             // 定义HttpClient    
  77.             HttpClient client = new DefaultHttpClient();    
  78.             // 实例化HTTP方法    
  79.             HttpPost request = new HttpPost();    
  80.             request.setURI(new URI(url));  
  81.               
  82.             //设置参数  
  83.             List<NameValuePair> nvps = new ArrayList<NameValuePair>();   
  84.             for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {  
  85.                 String name = (String) iter.next();  
  86.                 String value = String.valueOf(params.get(name));  
  87.                 nvps.add(new BasicNameValuePair(name, value));  
  88.                   
  89.                 //System.out.println(name +"-"+value);  
  90.             }  
  91.             request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));  
  92.               
  93.             HttpResponse response = client.execute(request);    
  94.             int code = response.getStatusLine().getStatusCode();  
  95.             if(code == 200){    //请求成功  
  96.                 in = new BufferedReader(new InputStreamReader(response.getEntity()    
  97.                         .getContent(),"utf-8"));  
  98.                 StringBuffer sb = new StringBuffer("");    
  99.                 String line = "";    
  100.                 String NL = System.getProperty("line.separator");    
  101.                 while ((line = in.readLine()) != null) {    
  102.                     sb.append(line + NL);    
  103.                 }  
  104.                   
  105.                 in.close();    
  106.                   
  107.                 return sb.toString();  
  108.             }  
  109.             else{   //  
  110.                 System.out.println("状态码:" + code);  
  111.                 return null;  
  112.             }  
  113.         }  
  114.         catch(Exception e){  
  115.             e.printStackTrace();  
  116.               
  117.             return null;  
  118.         }  
  119.     }  
  120.       
  121.     /** 
  122.      * post请求(用于请求json格式的参数) 
  123.      * @param url 
  124.      * @param params 
  125.      * @return 
  126.      */  
  127.     public static String doPost(String url, String params) throws Exception {  
  128.           
  129.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  130.         HttpPost httpPost = new HttpPost(url);// 创建httpPost     
  131.         httpPost.setHeader("Accept""application/json");   
  132.         httpPost.setHeader("Content-Type""application/json");  
  133.         String charSet = "UTF-8";  
  134.         StringEntity entity = new StringEntity(params, charSet);  
  135.         httpPost.setEntity(entity);          
  136.         CloseableHttpResponse response = null;  
  137.           
  138.         try {  
  139.               
  140.             response = httpclient.execute(httpPost);  
  141.             StatusLine status = response.getStatusLine();  
  142.             int state = status.getStatusCode();  
  143.             if (state == HttpStatus.SC_OK) {  
  144.                 HttpEntity responseEntity = response.getEntity();  
  145.                 String jsonString = EntityUtils.toString(responseEntity);  
  146.                 return jsonString;  
  147.             }  
  148.             else{  
  149.                  logger.error("请求返回:"+state+"("+url+")");  
  150.             }  
  151.         }  
  152.         finally {  
  153.             if (response != null) {  
  154.                 try {  
  155.                     response.close();  
  156.                 } catch (IOException e) {  
  157.                     e.printStackTrace();  
  158.                 }  
  159.             }  
  160.             try {  
  161.                 httpclient.close();  
  162.             } catch (IOException e) {  
  163.                 e.printStackTrace();  
  164.             }  
  165.         }  
  166.         return null;  
  167.     }  
  168.       
  169. }  

httpclient是一个非常常用的工具,在项目开发的时候,经常需要请求第三方的接口,我整理好了这段代码,以后回头找的时候就方便啦!

猜你喜欢

转载自blog.csdn.net/qq_42039607/article/details/80389614