使用httpClient连接池处理get或post请求
以前有一个自己写的: http://www.cnblogs.com/wenbronk/p/6482706.html
后来发现一个前辈写的更好的, 再此感谢一下, 确实比我写的那个好用些
1, 创建一个HttpClientPool
package com.iwhere.easy.travel.tool; import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; /**
* httpclient
* @author chenshiyuan
*
*/
public class HttpClientPool {
private static PoolingHttpClientConnectionManager cm = null;
static{
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal();
cm.setDefaultMaxPerRoute();
}
public static CloseableHttpClient getHttpClient(){
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(globalConfig).build();
return client;
} }
2, 处理get或post请求的类
url: 即为请求的url
method: 为请求的方法, 在此只处理 "get" 和 "post" 方法
map: 请求参数, 如果没有则传入 new HashMap<>();
package com.iwhere.easy.travel.tool; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSONObject; public class RequestTools { public static String processHttpRequest(String url, String requestMethod, Map<String, String> paramsMap) {
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
if ("post".equals(requestMethod)) {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type", "application/json");
for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
String value = paramsMap.get(key);
formparams.add(new BasicNameValuePair(key, value));
}
return doRequest(httppost, null, formparams);
} else if ("get".equals(requestMethod)) {
HttpGet httppost = new HttpGet(url);
for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) {
String key = it.next();
String value = paramsMap.get(key);
formparams.add(new BasicNameValuePair(key, value));
}
return doRequest(null, httppost, formparams);
}
return "";
} private static String doRequest(HttpPost httpPost, HttpGet httpGet, List<BasicNameValuePair> formparams) { try {
CloseableHttpResponse response = null;
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout().setConnectTimeout()
.build();
if (null != httpPost) {
uefEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(uefEntity);
httpPost.setConfig(requestConfig);
response = HttpClientPool.getHttpClient().execute(httpPost);
} else {
httpGet.setConfig(requestConfig);
response = HttpClientPool.getHttpClient().execute(httpGet);
}
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity, "UTF-8");
if (null == str || "".equals(str)) {
return "";
} else {
return str;
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return "";
}
}
3, 后来发现这个没法处理json格式的body, 所以写了个json格式的post请求方法
/**
* 处理json格式的body post请求
*
* @return
* @throws Exception
* @throws ClientProtocolException
*/
public static String processPostJson(String postUrl, JSONObject jsonObj) throws ClientProtocolException, Exception {
// HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(postUrl);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String str = null;
StringEntity s = new StringEntity(jsonObj.toJSONString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout().setConnectTimeout().build(); post.setEntity(s);
post.setConfig(requestConfig); CloseableHttpResponse response = HttpClientPool.getHttpClient().execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
str = convertStreamToString(instreams);
post.abort();
}
// System.out.println(str);
return str;
} private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
使用httpClient连接池处理get或post请求的更多相关文章
- httpclient连接池在ES Restful API请求中的应用
package com.wm.utils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http ...
- Http持久连接与HttpClient连接池
一.背景 HTTP协议是无状态的协议,即每一次请求都是互相独立的.因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接. HTTP协议是全双工的协议, ...
- Http 持久连接与 HttpClient 连接池
一.背景 HTTP协议是无状态的协议,即每一次请求都是互相独立的.因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接. HTTP协议是全双工的协议, ...
- HttpClient连接池
HttpClient连接池,发现对于高并发的请求,效率提升很大.虽然知道是因为建立了长连接,导致请求效率提升,但是对于内部的原理还是不太清楚.后来在网上看到了HTTP协议的发展史,里面提到了一个属性C ...
- HttpClient连接池的一些思考
前言 使用apache的httpclient进行http的交互处理已经很长时间了,而httpclient实例则使用了http连接池,想必大家也没有关心过连接池的管理.事实上,通过分析httpclien ...
- HttpClient实战三:Spring整合HttpClient连接池
简介 在微服务架构或者REST API项目中,使用Spring管理Bean是很常见的,在项目中HttpClient使用的一种最常见方式就是:使用Spring容器XML配置方式代替Java编码方式进行H ...
- httpclient: 设置连接池及超时配置,请求数据:PoolingHttpClientConnectionManager
public static void main(String[] args) throws Exception{ //httpclient连接池 //创建连接池 PoolingHttpClientCo ...
- springboot使用RestTemplate+httpclient连接池发送http消息
简介 RestTemplate是spring支持的一个请求http rest服务的模板对象,性质上有点像jdbcTemplate RestTemplate底层还是使用的httpclient(org.a ...
- HttpPoolUtils 连接池管理的GET POST请求
package com.nextjoy.projects.usercenter.util.http; import org.apache.http.Consts; import org.apache. ...
随机推荐
- iOS 5 故事板进阶(2)
让我们回到游戏排行窗口Ranking.创建一个 UITableViewController子类,命名为 RankingViewController. 编辑 RankingViewController. ...
- Java实现WordCount
GitHub项目地址:https://github.com/happyOwen/SoftwareEngineering wordcount项目要求: 程序处理用户需求的模式为:wc.exe [para ...
- WPF中得到一个控件相对其他控件的坐标
加入想得到按钮btnTest左上角相对于主窗体winTest的坐标,可以用如下方法:btnTest.TranslatePoint(new Point(0, 0), winTest)这个方法返回一个Po ...
- c# 输入多个数字,当输入不是数字时显示出刚输入的所有数并按降序
输入多个数字,当输入不是数字时显示出刚输入的所有数并按降序 class Program { static void Main(string[] args) { //定于一个集合 List<int ...
- 第五章 HashMap源码解析
5.1.对于HashMap需要掌握以下几点 Map的创建:HashMap() 往Map中添加键值对:即put(Object key, Object value)方法 获取Map中的单个对象:即get( ...
- UCS2-little endian转码(utf16)
public static void readFile(){ BufferedReader in = null; try { in = new BufferedReader(new InputStre ...
- Cordova - XCode10编译热更新插件错误解决方法!
操作系统:OSX10.14 XCode:10.1 热更新插件:https://github.com/nordnet/cordova-hot-code-push 这个热更新插件,在安卓下编译,没有问题, ...
- Yes,I know the way to learn Ens !
In recent years, translation has gone out of fashion as a way to learn a new language. A lot of peop ...
- docker 运行容器,安装Nginx
########################################## #运行容器 #安装Nginx #搜索.下载镜像 docker search nginx docker pull n ...
- 三,memcached服务的两种访问方式
memcached有两种访问方式,分别是使用telnet访问和使用php访问. 1,使用telnet访问memcacehd 在命令提示行输入, (1)连接memcached指令:telnet 127. ...