以前有一个自己写的: 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请求的更多相关文章

  1. httpclient连接池在ES Restful API请求中的应用

    package com.wm.utils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http ...

  2. Http持久连接与HttpClient连接池

    一.背景 HTTP协议是无状态的协议,即每一次请求都是互相独立的.因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接. HTTP协议是全双工的协议, ...

  3. Http 持久连接与 HttpClient 连接池

    一.背景 HTTP协议是无状态的协议,即每一次请求都是互相独立的.因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接. HTTP协议是全双工的协议, ...

  4. HttpClient连接池

    HttpClient连接池,发现对于高并发的请求,效率提升很大.虽然知道是因为建立了长连接,导致请求效率提升,但是对于内部的原理还是不太清楚.后来在网上看到了HTTP协议的发展史,里面提到了一个属性C ...

  5. HttpClient连接池的一些思考

    前言 使用apache的httpclient进行http的交互处理已经很长时间了,而httpclient实例则使用了http连接池,想必大家也没有关心过连接池的管理.事实上,通过分析httpclien ...

  6. HttpClient实战三:Spring整合HttpClient连接池

    简介 在微服务架构或者REST API项目中,使用Spring管理Bean是很常见的,在项目中HttpClient使用的一种最常见方式就是:使用Spring容器XML配置方式代替Java编码方式进行H ...

  7. httpclient: 设置连接池及超时配置,请求数据:PoolingHttpClientConnectionManager

    public static void main(String[] args) throws Exception{ //httpclient连接池 //创建连接池 PoolingHttpClientCo ...

  8. springboot使用RestTemplate+httpclient连接池发送http消息

    简介 RestTemplate是spring支持的一个请求http rest服务的模板对象,性质上有点像jdbcTemplate RestTemplate底层还是使用的httpclient(org.a ...

  9. HttpPoolUtils 连接池管理的GET POST请求

    package com.nextjoy.projects.usercenter.util.http; import org.apache.http.Consts; import org.apache. ...

随机推荐

  1. hdu 5035 指数分布无后效性

    http://acm.hdu.edu.cn/showproblem.php?pid=5035 n个柜台每个柜台服务的时间都满足指数分布t=p(k),求min(p(k)+t)的期望 指数分布一个有趣的特 ...

  2. mySQl数据库中不能插入中文的处理办法

    1. 修改MySQL安装目录下(C:\Program Files\MySQL\MySQL Server 5.5)的my.ini文件 设置: default-character-set=utf8 cha ...

  3. Android 体系架构

    什么是Android? 答:Android就是移动设备的软件栈,包括(一个完整的操作系统,中间件,关键应用程序), 底层是Linux内核,包括(安全管理, 内存管理,进程管理 ,电源管理,硬件驱动-) ...

  4. 【TypeScript】TypeScript 学习 5——方法

    在 JavaScript 中,有两种方式定义方法. 1.命名的方法 function add(x,y){ return x+y; } 2.匿名方法 var myAdd = function(x,y) ...

  5. [Openwrt 项目开发笔记]:Samba服务&vsFTP服务(四)

    [Openwrt项目开发笔记]系列文章传送门:http://www.cnblogs.com/double-win/p/3888399.html 正文: 在上一节中,我们讲述了如何在路由器上挂载U盘,以 ...

  6. Send or receive files via Xshell

    1. install lrzsz $ sudo apt-get install lrzsz 2. If you want to send file from your pc to pi, just d ...

  7. Easy Ui 的reload 问题

    当我删除某条数据时,删除成功后要刷新datagrid 这时调用reload方法就不成功,而要用下面的方式. 正确代码$('#fixedGrid').datagrid("reload" ...

  8. Sending Email In .NET Core 2.0

    Consider the following written in .NET Core 2.0. SmtpClient client = ) { UseDefaultCredentials = tru ...

  9. 基于jTopo的拓扑图设计工具库ujtopo

    绘制拓扑图有很多开源的工具,知乎上也有人回答了这个问题: https://www.zhihu.com/question/41026400/answer/118726253 ujtopo是基于jTopo ...

  10. ABP框架入门踩坑-使用MySQL

    使用MySQL ABP踩坑记录-目录 起因 因为我自用的服务器只是腾讯云1核1G的学生机,不方便装SQL Server,所以转而MySQL. 这里使用的MySQL版本号为 8.0. 解决方案 删除Qi ...