使用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. ...
随机推荐
- node.excel
今天突然间想起来用node如何操作excel,记得之前用Java的poi操作excel,感觉特别爽,计算机代替人的工作,非常有用,所以决定摸索一下. 在网上找了各种模块,有导出的,有导入的,有转为js ...
- FreeBSD查看即时网络流量
1.数据包 “netstat 1″一秒钟累计一次,”netstat 2″两秒钟累计一次.依此类推 2.查看网卡流量:”systat -if 1″每秒钟刷新一次,”systat -if 2″两秒钟刷新一 ...
- NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(转载)
原文地址:http://www.cnblogs.com/asxinyu/p/dotnet_Opensource_project_FluentValidation_1.html 阅读目录 1.基本介绍 ...
- 记一次golang的实践
之前做过一个深交所股票数据的接存储软件,消息的协议是这样. 协议文档在这 https://wenku.baidu.com/view/d102cd0b4a73f242336c1eb91a37f111f ...
- SQL学习笔记1
2018.10.15:周一 -- 返回前5个数据 SELECT TOP 5 * FROM Student; -- 返回前50%的数据 SELECT TOP 50 PERCENT * FROM ...
- js url 参数 转换成 json 对象数据
some=params&over=here => {"some":"params","over":"here&quo ...
- pageadmin CMS网站制作教程:模板概念解释
pageadmin CMS网站建设教程:模板概念解释 1.模板页 又叫视图页面,PageAdmin后台栏目或信息中用到的模板页面的统称,格式必须是.cshtml后缀文件,前端人员制作的页面默认都是ht ...
- MYsql 之多表查询.
http://www.cnblogs.com/wangfengming/articles/8067220.html
- FFmpeg编写的代码
//初始化解封装 av_register_all(); avformat_network_init(); avcodec_register_all(); //封装文件的上下文 ...
- [Swift实际操作]七、常见概念-(4)范围CGRect的使用详解
本文将为你演示区域对象CGRect的使用.你可以将区域对象,看作是点对象和尺寸对象的组合 首先导入需要使用到底界面工具框架 import UIKit 然后初始化一个区域对象,它的原点位于(0,0),宽 ...