org.apache.httpcomponents:httpclient 工具类

基于httpclient 版本4.4.1

因为http连接需要三次握手,在需要频繁调用时浪费资源和时间

故采用连接池的方式连接

  根据实际需要更改  连接池最大连接数、路由最大连接数

  另一个需要注意的是

   // 释放Socket流
     response.close();
     // 释放Connection
     // httpClient.close();
  1 import org.apache.http.HttpEntity;
  2 import org.apache.http.NameValuePair;
  3 import org.apache.http.client.config.RequestConfig;
  4 import org.apache.http.client.entity.UrlEncodedFormEntity;
  5 import org.apache.http.client.methods.CloseableHttpResponse;
  6 import org.apache.http.client.methods.HttpGet;
  7 import org.apache.http.client.methods.HttpPost;
  8 import org.apache.http.client.methods.HttpRequestBase;
  9 import org.apache.http.client.utils.URIBuilder;
 10 import org.apache.http.config.SocketConfig;
 11 import org.apache.http.entity.StringEntity;
 12 import org.apache.http.impl.client.CloseableHttpClient;
 13 import org.apache.http.impl.client.HttpClients;
 14 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 15 import org.apache.http.message.BasicNameValuePair;
 16 import org.apache.http.util.EntityUtils;
 17
 18 import java.io.IOException;
 19 import java.io.UnsupportedEncodingException;
 20 import java.net.URISyntaxException;
 21 import java.util.ArrayList;
 22 import java.util.Map;
 23
 24 /**
 25  * Created by lidada on 2017/6/9.
 26  */
 27 public class HttpClientUtils {
 28     private static PoolingHttpClientConnectionManager cm;
 29     private static String EMPTY_STR = "";
 30     private static String CONTENT_TYPE_UTF_8 = "UTF-8";
 31     private static String CONTENT_TYPE_GBK = "GBK";
 32     private static String CONTENT_TYPE_JSON = "application/json";
 33     private static final int CONNECTION_TIMEOUT_MS = 60000;
 34     private static final int SO_TIMEOUT_MS = 60000;
 35
 36     private static void init() {
 37         if (cm == null) {
 38             cm = new PoolingHttpClientConnectionManager();
 39             cm.setMaxTotal(50);// 整个连接池最大连接数
 40             cm.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
 41             SocketConfig sc = SocketConfig.custom().setSoTimeout(SO_TIMEOUT_MS).build();
 42             cm.setDefaultSocketConfig(sc);
 43         }
 44     }
 45
 46     /**
 47      * 通过连接池获取HttpClient
 48      *
 49      * @return
 50      */
 51     private static CloseableHttpClient getHttpClient() {
 52         init();
 53         return HttpClients.custom().setConnectionManager(cm).setConnectionManagerShared(true) .build();
 54     }
 55
 56     public static String httpGetRequest(String url) {
 57         HttpGet httpGet = new HttpGet(url);
 58         return getResult(httpGet);
 59     }
 60
 61     public static String httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException {
 62         URIBuilder ub = new URIBuilder();
 63         ub.setPath(url);
 64
 65         ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
 66         ub.setParameters(pairs);
 67
 68         HttpGet httpGet = new HttpGet(ub.build());
 69         return getResult(httpGet);
 70     }
 71
 72     public static String httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params)
 73             throws URISyntaxException {
 74         URIBuilder ub = new URIBuilder();
 75         ub.setPath(url);
 76
 77         ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
 78         ub.setParameters(pairs);
 79
 80         HttpGet httpGet = new HttpGet(ub.build());
 81         for (Map.Entry<String, Object> param : headers.entrySet()) {
 82             httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
 83         }
 84         return getResult(httpGet);
 85     }
 86
 87     public static String httpPostRequest(String url) {
 88         HttpPost httpPost = new HttpPost(url);
 89         return getResult(httpPost);
 90     }
 91
 92     public static String httpPostRequest(String url, Map<String, Object> params) throws UnsupportedEncodingException {
 93         HttpPost httpPost = new HttpPost(url);
 94         ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
 95         httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8));
 96         return getResult(httpPost);
 97     }
 98
 99     public static String httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params)
100             throws UnsupportedEncodingException {
101         HttpPost httpPost = new HttpPost(url);
102
103         for (Map.Entry<String, Object> param : headers.entrySet()) {
104             httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
105         }
106
107         ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
108         httpPost.setEntity(new UrlEncodedFormEntity(pairs, CONTENT_TYPE_UTF_8));
109
110         return getResult(httpPost);
111     }
112
113     public static String httpPostJSON(String url, String json) throws UnsupportedEncodingException {
114         HttpPost httpPost = new HttpPost(url);
115         StringEntity s = new StringEntity(json);
116         s.setContentEncoding(CONTENT_TYPE_UTF_8);
117         s.setContentType(CONTENT_TYPE_JSON);// 发送json数据需要设置contentType
118         httpPost.setEntity(s);
119         return getResult(httpPost);
120     }
121
122
123     private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
124         ArrayList<NameValuePair> pairs = new ArrayList<>();
125         for (Map.Entry<String, Object> param : params.entrySet()) {
126             pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
127         }
128
129         return pairs;
130     }
131
132     /**
133      * 处理Http请求
134      *
135      * @param request
136      * @return
137      */
138     private static String getResult(HttpRequestBase request) {
139
140         RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT);
141         config.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
142         config.setSocketTimeout(SO_TIMEOUT_MS);
143
144         request.setConfig(config.build());
145
146         // CloseableHttpClient httpClient = HttpClients.createDefault();
147         CloseableHttpClient httpClient = getHttpClient();
148         CloseableHttpResponse response = null;
149         try {
150             response = httpClient.execute(request);
151             // response.getStatusLine().getStatusCode();
152             HttpEntity entity = response.getEntity();
153             if (entity != null) {
154                 // long len = entity.getContentLength();// -1 表示长度未知
155                 return EntityUtils.toString(entity);
156             }
157         } catch (IOException e) {
158             e.printStackTrace();
159         } finally {
160             try {
161                 // 释放Socket流
162                 response.close();
163                 // 释放Connection
164                 // httpClient.close();
165             } catch (IOException e) {
166                 e.printStackTrace();
167             }
168         }
169
170         return EMPTY_STR;
171     }
172
173 }
时间: 2024-11-07 20:36:58

org.apache.httpcomponents:httpclient 工具类的相关文章

使用单例模式实现自己的HttpClient工具类

引子 在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient 来方便我们使用各种Http服务.你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求(当然它的功 能远不止这些). 比如你只需以下几行代码就能发出一个简单的GET请求并打印响应结果: try { // 创建一个默认的HttpClient HttpClient httpclient =new Default

轻松把玩HttpClient之封装HttpClient工具类(二),插件式配置HttpClient对象

上一篇文章中,简单分享一下封装HttpClient工具类的思路及部分代码,本文将分享如何实现插件式配置HttpClient对象. 如果你看过我前面的几篇关于HttpClient的文章或者官网示例,应该都知道HttpClient对象在创建时,都可以设置各种参数,但是却没有简单的进行封装,比如对我来说比较重要的3个:代理.ssl(包含绕过证书验证和自定义证书验证).超时.还需要自己写.所以这里我就简单封装了一下,顺便还封装了一个连接池的配置. 其实说是插件式配置,那是高大上的说法,说白了,就是采用了

Apache commons lang工具类学习笔记(2)--StringUtils

StringUtils工具类具有对String具有简单而强大的处理能力,从检查空串到分割字符串,到生成格式化的字符串,使用都很方便简洁,能减少很多代码量; 详细的使用方法可以参考下面的例子或者官方的API(http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#isAlpha(java.lang.CharSequence)) packa

org.apache.httpcomponents.httpclient

apache org doc :http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e49 依赖: <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artif

java httpclient工具类

meven <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> -- 代码 import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.

HttpClient工具类(二)

package com.cucpay.tradeportal.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.cert.CertificateException; import java.security.cer

轻松把玩HttpClient之封装HttpClient工具类(三),插件式配置Header

上篇文章介绍了插件式配置HttpClient,本文将介绍插件式配置Header. 为什么要配置header在前面已经提到了,还里再简单说一下,要使用HttpClient模拟请求,去访问各种接口或者网站资源,都有可能有各种限制,比如说java客户端模拟访问csdn博客,就必须设置User-Agent,否则就报错了.还有各种其他情况,必须的设置一些特定的Header,才能请求成功,或者才能不出问题. 好了就说这么多,本次还是采用构造者模式的级联调用方式,来完成该工具类.在该工具类中,为所有常用的Ht

Android开发实现HttpClient工具类

在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求(当然它的功能远不止这些). 比如你只需以下几行代码就能发出一个简单的GET请求并打印响应结果: try {         // 创建一个默认的HttpClient         HttpClient httpclient =

httpclient工具类,post请求发送json字符串参数,中文乱码处理

在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文的时候在发送端数据正常但是到了服务器端就中文乱码了. 解决办法: 发送端进行设置编码如下: 工具类: 1 package com.Util; 2 3 import com.google.common.base.Charsets; 4 import org.apache.http.HttpEntity