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

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


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

原文地址:https://www.cnblogs.com/w-xibao/p/8482547.html