HttpClient請求工具類

無畏D塵埃發表於2019-01-05
  1 package com.yangche.utils;
  2 
  3 import org.apache.http.NameValuePair;
  4 import org.apache.http.client.ClientProtocolException;
  5 import org.apache.http.client.entity.UrlEncodedFormEntity;
  6 import org.apache.http.client.methods.*;
  7 import org.apache.http.client.utils.URIBuilder;
  8 import org.apache.http.entity.ContentType;
  9 import org.apache.http.entity.StringEntity;
 10 import org.apache.http.impl.client.CloseableHttpClient;
 11 import org.apache.http.impl.client.HttpClients;
 12 import org.apache.http.message.BasicNameValuePair;
 13 import org.apache.http.util.EntityUtils;
 14 import org.springframework.util.StringUtils;
 15 
 16 import java.io.IOException;
 17 import java.io.UnsupportedEncodingException;
 18 import java.net.URI;
 19 import java.net.URISyntaxException;
 20 import java.util.ArrayList;
 21 import java.util.List;
 22 import java.util.Map;
 23 
 24 public class HttpClientUtil {
 25     public static String doGet(String url, Map<String,Object> param){
 26         //建立httpclient物件
 27         CloseableHttpClient httpClient = HttpClients.createDefault();
 28         String resultString="";
 29         CloseableHttpResponse response=null;
 30         try {
 31             URIBuilder builder=new URIBuilder(url);
 32             if(param!=null){
 33                 for (String key:param.keySet()){
 34                     if(param.get(key) instanceof List){
 35                         List list=(List)param.get(key);
 36                         for (Object liString:list){
 37                             builder.addParameter(key,String.valueOf(liString));
 38                         }
 39                     }else {
 40                         builder.addParameter(key,String.valueOf(param.get(key)));
 41                     }
 42                 }
 43             }
 44             URI uri=builder.build();
 45             //建立httpGet請求
 46             HttpGet httpGet=new HttpGet(uri);
 47             //執行請求
 48             response=httpClient.execute(httpGet);
 49             resultString= EntityUtils.toString(response.getEntity(),"UTF-8");
 50         } catch (URISyntaxException e) {
 51             e.printStackTrace();
 52         } catch (ClientProtocolException e) {
 53             e.printStackTrace();
 54         } catch (IOException e) {
 55             e.printStackTrace();
 56         }finally {
 57             try {
 58                 if(response!=null){
 59                     response.close();
 60                 }
 61                 httpClient.close();
 62             } catch (IOException e) {
 63                 e.printStackTrace();
 64             }
 65         }
 66         return resultString;
 67     }
 68     public static String doGet(String url){
 69         return doGet(url,null);
 70     }
 71     public static String doPost(String url,Map<String,String> param){
 72         //建立httpclient物件
 73         CloseableHttpClient httpClient = HttpClients.createDefault();
 74         CloseableHttpResponse response=null;
 75         String resultString="";
 76         //建立httpPost請求
 77         HttpPost httpPost = new HttpPost(url);
 78         //建立引數列表
 79         if(param!=null){
 80             List<NameValuePair> paramList=new ArrayList<>();
 81             for (String key:param.keySet()){
 82                 paramList.add(new BasicNameValuePair(key,param.get(key)));
 83             }
 84             try {
 85                 //模擬表單
 86                 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(paramList);
 87                 httpPost.setEntity(entity);
 88                 //執行http請求
 89                 response=httpClient.execute(httpPost);
 90                 resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
 91             } catch (UnsupportedEncodingException e) {
 92                 e.printStackTrace();
 93             } catch (ClientProtocolException e) {
 94                 e.printStackTrace();
 95             } catch (IOException e) {
 96                 e.printStackTrace();
 97             }finally {
 98                 try {
 99                     response.close();
100                 } catch (IOException e) {
101                     e.printStackTrace();
102                 }
103             }
104         }
105         return resultString;
106     }
107     public static String doPost(String url){
108         return doPost(url,null);
109     }
110 
111     /**
112      * restful請求
113      * @param url
114      * @param requestType 請求型別:post、delete、patch
115      * @param json
116      * @return
117      */
118     public static String doRequest(String url,String requestType,String json){
119         //建立HttpClient物件
120         CloseableHttpClient httpClient=HttpClients.createDefault();
121         CloseableHttpResponse response=null;
122         String resultString="";
123         try {
124             //建立不同型別的請求
125             HttpPost httpPost=new HttpPost(url);
126             HttpDeleteWithBody httpDelete =new HttpDeleteWithBody(url);
127             HttpPatch httpPatch=new HttpPatch(url);
128             //建立請求內容
129             StringEntity entity=new StringEntity(json, ContentType.APPLICATION_JSON);
130             //執行http請求
131             if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("post")){
132                 httpPost.setEntity(entity);
133                 response=httpClient.execute(httpPost);
134             }else if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("delete")){
135                 httpDelete.setEntity(entity);
136                 response=httpClient.execute(httpDelete);
137             }else if(!StringUtils.isEmpty(requestType)&&requestType.equalsIgnoreCase("patch")){
138                 httpPatch.setEntity(entity);
139                 response=httpClient.execute(httpPatch);
140             }
141             resultString=EntityUtils.toString(response.getEntity(),"UTF-8");
142         } catch (IOException e) {
143             e.printStackTrace();
144         } finally {
145             try {
146                 response.close();
147             } catch (IOException e) {
148                 e.printStackTrace();
149             }
150         }
151         return resultString;
152     }
153 
154     private static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
155         public static final String METHOD_NAME="DELETE";
156         @Override
157         public String getMethod() {
158             return METHOD_NAME;
159         }
160         public HttpDeleteWithBody (final String uri){
161             super();
162             setURI(URI.create(uri));
163         }
164         public HttpDeleteWithBody (final URI uri){
165             super();
166             setURI(uri);
167         }
168         public HttpDeleteWithBody(){
169             super();
170         }
171     }
172 }
以上所需的maven依賴如下:
 1 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
 2 <dependency>
 3     <groupId>org.apache.httpcomponents</groupId>
 4     <artifactId>httpcore</artifactId>
 5     <version>4.4.10</version>
 6 </dependency>
 7 
 8 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
 9 <dependency>
10     <groupId>org.apache.httpcomponents</groupId>
11     <artifactId>httpclient</artifactId>
12     <version>4.5.6</version>
13 </dependency>

 

相關文章