以前有一个自己写的: 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. javascript 问题

    两个数组比较:a.sort().toString() == b.sort().toString() for循环内有异步方法时,需要闭包 JSON.parse(data)出错时(提示.[nodejs中] ...

  2. What if you are involved in an automobile accident in the US

    What if you are involved in an automobile accident in the US With increasing Chinese tourists and vi ...

  3. "名字好难想队“团队项目

    团队展示 1.队名:名字好难想队 2.队员介绍 姓名 学号 岗位 黎扬乐(组长) 3116004689 程序,测试 李世潇 3116004690 策划,美术,动画 梁耀 3116004691 项目管理 ...

  4. [Ubuntu]管理开机启动项的软件

    sudo apt-get install sysv-rc-conf

  5. FreeBSD下面安装PostgreSQL。

    1.确认pkg版本大于1.1.4,可以用pkg -v查看,如果小于此版本,请升级.2.在/usr/local/etc/pkg.conf文件中,删除掉repository相关的语句,像PACKAGESI ...

  6. CSharp程序员学Android开发---1.初识AndriodIDE,掌握工具使用

    最近公司组织项目组成员开发一个Android项目的Demo,之前没有人有Andoid方面的开发经验,都是开发C#的. 虽说项目要求并不是很高,但是对于没有这方面经验的人来说,第一步是最困难的. 项目历 ...

  7. .Net core,EFCore 入门

    我在百度上搜了一下.net  core和efcore 入门案例.好多博客都是大概说了一下做法,对于小白而言还是一头雾水,我今天就抽出一点时间,写一个详细的入门小案例,就一张表没有什么业务可言.主要是操 ...

  8. Gzip压缩和解压

    /// <summary> /// 将传入字符串以GZip算法压缩后,返回Base64编码字符 /// </summary> /// <param name=" ...

  9. 关于Select选中问题

    jquery根据text选中option的问题: 网上找了好多,但发现因为jquery版本问题,很多并不能用.   最后成功了,写法如下:   $('#shop option:contains(' + ...

  10. SL 的 DATAGRID中如何加入计算列?

    例如,我的数据库中实体表对应到EF中的实体类是 class { public int  F1; public int F2; } 我在服务端做domainservice 我在SL端使用wcf ria, ...