httpClient

本文介绍了一个Java实现的HTTP客户端工具类,支持GET和POST请求,包括文件上传功能。该工具类通过Apache HttpClient实现了对HTTP请求的管理和执行,并对SSL连接进行了信任自签名证书的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.File;
  4 import java.io.IOException;
  5 import java.security.KeyManagementException;
  6 import java.security.KeyStoreException;
  7 import java.security.NoSuchAlgorithmException;
  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.HttpStatus;
 14 import org.apache.http.client.config.RequestConfig;
 15 import org.apache.http.client.methods.CloseableHttpResponse;
 16 import org.apache.http.client.methods.HttpGet;
 17 import org.apache.http.client.methods.HttpPost;
 18 import org.apache.http.config.Registry;
 19 import org.apache.http.config.RegistryBuilder;
 20 import org.apache.http.conn.socket.ConnectionSocketFactory;
 21 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
 22 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 23 import org.apache.http.conn.ssl.SSLContextBuilder;
 24 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
 25 import org.apache.http.entity.ContentType;
 26 import org.apache.http.entity.StringEntity;
 27 import org.apache.http.entity.mime.MultipartEntityBuilder;
 28 import org.apache.http.entity.mime.content.FileBody;
 29 import org.apache.http.entity.mime.content.StringBody;
 30 import org.apache.http.impl.client.CloseableHttpClient;
 31 import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
 32 import org.apache.http.impl.client.HttpClients;
 33 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 34 import org.apache.http.util.EntityUtils;
 35 
 36 /**
 37  * 
 38  * @author H__D
 39  * @date 2016年10月19日 上午11:27:25
 40  *
 41  */
 42 public class HttpClientUtil {
 43 
 44     // utf-8字符编码
 45     public static final String CHARSET_UTF_8 = "utf-8";
 46 
 47     // HTTP内容类型。
 48     public static final String CONTENT_TYPE_TEXT_HTML = "text/xml";
 49 
 50     // HTTP内容类型。相当于form表单的形式,提交数据
 51     public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded";
 52 
 53     // HTTP内容类型。相当于form表单的形式,提交数据
 54     public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8";
 55     
 56 
 57     // 连接管理器
 58     private static PoolingHttpClientConnectionManager pool;
 59 
 60     // 请求配置
 61     private static RequestConfig requestConfig;
 62 
 63     static {
 64         
 65         try {
 66             //System.out.println("初始化HttpClientTest~~~开始");
 67             SSLContextBuilder builder = new SSLContextBuilder();
 68             builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
 69             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
 70                     builder.build());
 71             // 配置同时支持 HTTP 和 HTPPS
 72             Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register(
 73                     "http", PlainConnectionSocketFactory.getSocketFactory()).register(
 74                     "https", sslsf).build();
 75             // 初始化连接管理器
 76             pool = new PoolingHttpClientConnectionManager(
 77                     socketFactoryRegistry);
 78             // 将最大连接数增加到200,实际项目最好从配置文件中读取这个值
 79             pool.setMaxTotal(200);
 80             // 设置最大路由
 81             pool.setDefaultMaxPerRoute(2);
 82             // 根据默认超时限制初始化requestConfig
 83             int socketTimeout = 10000;
 84             int connectTimeout = 10000;
 85             int connectionRequestTimeout = 10000;
 86             requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
 87                     connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
 88                     connectTimeout).build();
 89 
 90             //System.out.println("初始化HttpClientTest~~~结束");
 91         } catch (NoSuchAlgorithmException e) {
 92             e.printStackTrace();
 93         } catch (KeyStoreException e) {
 94             e.printStackTrace();
 95         } catch (KeyManagementException e) {
 96             e.printStackTrace();
 97         }
 98         
 99 
100         // 设置请求超时时间
101         requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(50000)
102                 .setConnectionRequestTimeout(50000).build();
103     }
104 
105     public static CloseableHttpClient getHttpClient() {
106         
107         CloseableHttpClient httpClient = HttpClients.custom()
108                 // 设置连接池管理
109                 .setConnectionManager(pool)
110                 // 设置请求配置
111                 .setDefaultRequestConfig(requestConfig)
112                 // 设置重试次数
113                 .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
114                 .build();
115         
116         return httpClient;
117     }
118 
119     /**
120      * 发送Post请求
121      * 
122      * @param httpPost
123      * @return
124      */
125     private static String sendHttpPost(HttpPost httpPost) {
126 
127         CloseableHttpClient httpClient = null;
128         CloseableHttpResponse response = null;
129         // 响应内容
130         String responseContent = null;
131         try {
132             // 创建默认的httpClient实例.
133             httpClient = getHttpClient();
134             // 配置请求信息
135             httpPost.setConfig(requestConfig);
136             // 执行请求
137             response = httpClient.execute(httpPost);
138             // 得到响应实例
139             HttpEntity entity = response.getEntity();
140 
141             // 可以获得响应头
142             // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
143             // for (Header header : headers) {
144             // System.out.println(header.getName());
145             // }
146 
147             // 得到响应类型
148             // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
149 
150             // 判断响应状态
151             if (response.getStatusLine().getStatusCode() >= 300) {
152                 throw new Exception(
153                         "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
154             }
155 
156             if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
157                 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
158                 EntityUtils.consume(entity);
159             }
160 
161         } catch (Exception e) {
162             e.printStackTrace();
163         } finally {
164             try {
165                 // 释放资源
166                 if (response != null) {
167                     response.close();
168                 }
169             } catch (IOException e) {
170                 e.printStackTrace();
171             }
172         }
173         return responseContent;
174     }
175 
176     /**
177      * 发送Get请求
178      * 
179      * @param httpGet
180      * @return
181      */
182     private static String sendHttpGet(HttpGet httpGet) {
183 
184         CloseableHttpClient httpClient = null;
185         CloseableHttpResponse response = null;
186         // 响应内容
187         String responseContent = null;
188         try {
189             // 创建默认的httpClient实例.
190             httpClient = getHttpClient();
191             // 配置请求信息
192             httpGet.setConfig(requestConfig);
193             // 执行请求
194             response = httpClient.execute(httpGet);
195             // 得到响应实例
196             HttpEntity entity = response.getEntity();
197 
198             // 可以获得响应头
199             // Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
200             // for (Header header : headers) {
201             // System.out.println(header.getName());
202             // }
203 
204             // 得到响应类型
205             // System.out.println(ContentType.getOrDefault(response.getEntity()).getMimeType());
206 
207             // 判断响应状态
208             if (response.getStatusLine().getStatusCode() >= 300) {
209                 throw new Exception(
210                         "HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
211             }
212 
213             if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
214                 responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
215                 EntityUtils.consume(entity);
216             }
217 
218         } catch (Exception e) {
219             e.printStackTrace();
220         } finally {
221             try {
222                 // 释放资源
223                 if (response != null) {
224                     response.close();
225                 }
226             } catch (IOException e) {
227                 e.printStackTrace();
228             }
229         }
230         return responseContent;
231     }
232     
233     
234     
235     /**
236      * 发送 post请求
237      * 
238      * @param httpUrl
239      *            地址
240      */
241     public static String sendHttpPost(String httpUrl) {
242         // 创建httpPost
243         HttpPost httpPost = new HttpPost(httpUrl);
244         return sendHttpPost(httpPost);
245     }
246 
247     /**
248      * 发送 get请求
249      * 
250      * @param httpUrl
251      */
252     public static String sendHttpGet(String httpUrl) {
253         // 创建get请求
254         HttpGet httpGet = new HttpGet(httpUrl);
255         return sendHttpGet(httpGet);
256     }
257     
258     
259 
260     /**
261      * 发送 post请求(带文件)
262      * 
263      * @param httpUrl
264      *            地址
265      * @param maps
266      *            参数
267      * @param fileLists
268      *            附件
269      */
270     public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
271         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
272         MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
273         if (maps != null) {
274             for (String key : maps.keySet()) {
275                 meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
276             }
277         }
278         if (fileLists != null) {
279             for (File file : fileLists) {
280                 FileBody fileBody = new FileBody(file);
281                 meBuilder.addPart("files", fileBody);
282             }
283         }
284         HttpEntity reqEntity = meBuilder.build();
285         httpPost.setEntity(reqEntity);
286         return sendHttpPost(httpPost);
287     }
288 
289     /**
290      * 发送 post请求
291      * 
292      * @param httpUrl
293      *            地址
294      * @param params
295      *            参数(格式:key1=value1&key2=value2)
296      * 
297      */
298     public static String sendHttpPost(String httpUrl, String params) {
299         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
300         try {
301             // 设置参数
302             if (params != null && params.trim().length() > 0) {
303                 StringEntity stringEntity = new StringEntity(params, "UTF-8");
304                 stringEntity.setContentType(CONTENT_TYPE_FORM_URL);
305                 httpPost.setEntity(stringEntity);
306             }
307         } catch (Exception e) {
308             e.printStackTrace();
309         }
310         return sendHttpPost(httpPost);
311     }
312 
313     /**
314      * 发送 post请求
315      * 
316      * @param maps
317      *            参数
318      */
319     public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
320         String parem = convertStringParamter(maps);
321         return sendHttpPost(httpUrl, parem);
322     }
323 
324     
325     
326     
327     /**
328      * 发送 post请求 发送json数据
329      * 
330      * @param httpUrl
331      *            地址
332      * @param paramsJson
333      *            参数(格式 json)
334      * 
335      */
336     public static String sendHttpPostJson(String httpUrl, String paramsJson) {
337         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
338         try {
339             // 设置参数
340             if (paramsJson != null && paramsJson.trim().length() > 0) {
341                 StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
342                 stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
343                 httpPost.setEntity(stringEntity);
344             }
345         } catch (Exception e) {
346             e.printStackTrace();
347         }
348         return sendHttpPost(httpPost);
349     }
350     
351     /**
352      * 发送 post请求 发送xml数据
353      * 
354      * @param httpUrl   地址
355      * @param paramsXml  参数(格式 Xml)
356      * 
357      */
358     public static String sendHttpPostXml(String httpUrl, String paramsXml) {
359         HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
360         try {
361             // 设置参数
362             if (paramsXml != null && paramsXml.trim().length() > 0) {
363                 StringEntity stringEntity = new StringEntity(paramsXml, "UTF-8");
364                 stringEntity.setContentType(CONTENT_TYPE_TEXT_HTML);
365                 httpPost.setEntity(stringEntity);
366             }
367         } catch (Exception e) {
368             e.printStackTrace();
369         }
370         return sendHttpPost(httpPost);
371     }
372     
373 
374     /**
375      * 将map集合的键值对转化成:key1=value1&key2=value2 的形式
376      * 
377      * @param parameterMap
378      *            需要转化的键值对集合
379      * @return 字符串
380      */
381     public static String convertStringParamter(Map parameterMap) {
382         StringBuffer parameterBuffer = new StringBuffer();
383         if (parameterMap != null) {
384             Iterator iterator = parameterMap.keySet().iterator();
385             String key = null;
386             String value = null;
387             while (iterator.hasNext()) {
388                 key = (String) iterator.next();
389                 if (parameterMap.get(key) != null) {
390                     value = (String) parameterMap.get(key);
391                 } else {
392                     value = "";
393                 }
394                 parameterBuffer.append(key).append("=").append(value);
395                 if (iterator.hasNext()) {
396                     parameterBuffer.append("&");
397                 }
398             }
399         }
400         return parameterBuffer.toString();
401     }
402 
403     public static void main(String[] args) throws Exception {
404         
405         System.out.println(sendHttpGet("http://www.baidu.com"));
406     
407     }
408 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值