使用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. ...
随机推荐
- This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed(在64位模式下运行安装了32位的Oracle客户端组件时,会发生此问题)
部署win服务时出现下面的问题: 在事件查看器中看到如下错误: 日志名称: Application来源: ***调度服务日期: 2014/5/21 12:53:21事件 ID: 0任务类别: 无级别: ...
- calltree+graphviz 绘出项目函数调用图
install calltree: download from http://linux.softpedia.com/progDownload/calltree-Download-971.html f ...
- 在Windows Server 2012 R2域环境中禁用(取消)密码复杂策略
windows server 2012域环境默认启用密码复杂策略,例如: 至少有六个字符长,包含以下四类字符中的三类字符:英文大写字母(A 到 Z),英文小写字母(a 到 z),10 个基本数字(0 ...
- Visual Studio模板
转载自MSDN,此文仅作参考. http://msdn.microsoft.com/zh-cn/library/6db0hwky(VS.80).aspx 1. 如何导入“项目模板(Project Te ...
- 自己从0开始学习Unity的笔记 I (C#字符串转换为数字)
我基本上从0开始学习编程,运算符基本上跳过,因为知道了 “=”这个符号相当于赋值,然后“==”才是等于,其他和普通运算符号差不都,也就跳过了. 最基础的赋值那种,我看了下代码,似乎没什么难度,估计新手 ...
- 关于ORACLE的字符窜存储(未完善,欢迎补充)
oracle中常见的用于存储字符串的数据类型有: 数据类型 是否定长 最多存储数 效率排行 备注 是否oracle特有 英文占位 中文占位 char 是 2000 比VARCHAR2稍高 char的长 ...
- ASP.NET MVC 实现带论坛功能的网站 第一步——-实现用户注册.
首先我们要实现用户的注册功能.进入visual studio 点击文件->新建->项目->选择ASP.NET Web应用程序(.NET Framework)->选择的模板为MV ...
- 3D Spherical Geometry Kernel( Geometry Kernels) CGAL 4.13 -User Manual
Introduction The goal of the 3D spherical kernel is to offer to the user a large set of functionalit ...
- In file included from adlist.c:34:0: zmalloc.h:50:31: 致命错误:jemalloc/jemalloc.h:没有那个文件或目录
问题: In file included from adlist.c:34:0:zmalloc.h:50:31: 致命错误:jemalloc/jemalloc.h:没有那个文件或目录 解决: make ...
- 792. Number of Matching Subsequences
Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of ...