HttpClient的get+post请求使用
啥都不说,先上代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger; import com.alibaba.fastjson.JSONObject; /**
* http请求工具类
* Created by swordxu on 15/8/5.
*/
public class HttpClientUtils {
private static Logger logger = Logger.getLogger(HttpClientUtils.class); //设置连接池线程最大数量
private static final int MAX_TOTAL = 500;
//设置单个路由最大的连接线程数量
private static final int MAX_ROUTE_TOTAL = 500; private static final int REQUEST_TIMEOUT = 25000; private static final int REQUEST_SOCKET_TIME = 25000; private static final String ENCODING_UTF_8 = "UTF-8"; private static HttpClientBuilder httpBulder = null;
private static CloseableHttpClient httpClient = null; static{ if (httpClient == null) {
ConnectionSocketFactory httpFactory = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", httpFactory).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL); httpClient = HttpClients.custom().setConnectionManager(cm)
.disableAutomaticRetries().build();
} } /**
* get请求方式
* @param uri 请求url
* @return
*/
public String doGet(String uri) throws Exception{
long b = System.currentTimeMillis();
//CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpGet httpget = null;
try {
logger.debug("executing get request uri :" + uri); httpget = new HttpGet(uri);
//httpClient = HttpClients.createDefault();
response = httpClient.execute(httpget); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
logger.debug("response body :" + sb);
long e = System.currentTimeMillis();
logger.debug("executing post request time:" + (e -b)); EntityUtils.consume(entity);//关闭httpEntity流 return sb.toString();
}else{
throw new Exception(response.getStatusLine().getStatusCode()+"");
}
} catch (ClientProtocolException e) {
logger.error("Failed to get request uri: "+uri,e);
throw new RuntimeException("Failed to post request uri: "+uri,e);
} catch (IOException e) {
logger.error("Failed to get request uri: "+uri,e);
throw new RuntimeException("Failed to post request uri: "+uri,e);
}finally {
close(httpget,response);
}
}
/**
* post 请求并返回实体对象
* @param url 请求url
* @param paramaters 请求参数
* @param clazz 返回Class
* @return
* @throws Exception
*/
public static <T> T doPost(String url, Map<String, String> paramaters,Class<T> clazz) throws Exception{
String ret = post(url, paramaters, null);
return null != ret ? JSONObject.parseObject(ret, clazz) : null;
} /**
* 发送POST请求
* @param uri
* @return
*/
public static String post(String uri) throws Exception{
return post(uri, null);
} /**
* 发送POST请求
* @param uri
* @param paramMap 请求参数
* @return
*/
public static String post(String uri, Map<String, String> paramMap) throws Exception{
return post(uri, paramMap, null);
} /**
* post 请求
* @param uri 请求url
* @param paramMap 请求参数
* @param charset 请求编码
* @return
* @throws Exception
*/
public static String post(String uri, Map<String, String> paramMap,String charset) throws Exception{
long b = System.currentTimeMillis();
CloseableHttpResponse response = null;
//CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
try {
logger.debug("executing post request url:"+uri); httpPost = new HttpPost(uri);
httpPost.setEntity(new UrlEncodedFormEntity(handleData(paramMap),null == charset ? ENCODING_UTF_8 : charset)); //httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
logger.debug("response body :" + sb);
long e = System.currentTimeMillis();
logger.debug("executing post request time:" + (e -b)); EntityUtils.consume(entity);//关闭流 return sb.toString();
}else{
throw new Exception(response.getStatusLine().getStatusCode()+"");
}
} catch (Exception e) {
throw e;
}finally{
close(httpPost,response);
}
} /**
* post 请求
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params) throws Exception{
return post(url, params, null);
} /**
* post 请求
* @param url
* @param json
* @return
*/
public static <T> T doPost(String url, String json, Class<T> clazz) throws Exception{
String ret = doPost(url, json);
return null != ret ? JSONObject.parseObject(ret, clazz) : null;
} /**
* post 请求
* @param url
* @param json
* @return
*/
public static String doPost(String url, String json) throws Exception{
CloseableHttpResponse response = null;
HttpPost httpPost = null;
long b = System.currentTimeMillis();
try {
logger.debug("executing post request url:" + url); StringEntity s = new StringEntity(json,"UTF-8");
s.setContentType("application/json"); httpPost = new HttpPost(url);
httpPost.setEntity(s); //httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
logger.debug("response body :" + sb);
long e = System.currentTimeMillis();
logger.debug("executing post request time:" + (e -b)); EntityUtils.consume(entity);//关闭流 return sb.toString();
}else{
throw new Exception(response.getStatusLine().getStatusCode()+"");
}
}finally{
close(httpPost,response);
}
} /**
* 处理map数据
* @param postData 请求数据
* @return
*/
private static List<NameValuePair> handleData(Map<String, String> postData) {
List<NameValuePair> datas = new ArrayList<NameValuePair>();
for (Map.Entry<String,String> entry : postData.entrySet()) {
datas.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return datas;
}
/**
* 关闭链接
* @param request
* @param response
*/
private static void close(HttpRequestBase request,CloseableHttpResponse response){
if(null != response){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != request){
request.releaseConnection();
}
}
1、http的静态变量的相关设置
static{
if (httpClient == null) {
ConnectionSocketFactory httpFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", httpFactory).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(MAX_TOTAL);
cm.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL);
httpClient = HttpClients.custom().setConnectionManager(cm)
.disableAutomaticRetries().build();
}
}
2.httpCliet的调用
String strResult = "";
JSONObject jobj = new JSONObject();
jobj.put("wxacc", wxacc);
jobj.put("password", password);
jobj.put("smallClassId", smallClassId);
jobj.put("reportName", reportName);
jobj.put("mobile", mobile);
jobj.put("address", address);
jobj.put("description", description);
jobj.put("position", position);
jobj.put("files", files);
jobj.put("wxEvtFileList", wxEvtFileList);
jobj.put("isreceipt", "true"); String conResult;
try {
conResult = HttpClientUtils.doPost(saveEvtPreUrl, jobj.toJSONString());
Head head = JSON.parseObject(conResult, Head.class);
logger.debug(head.toString());
} catch (Exception e) {
e.printStackTrace();
} return strResult;
完~
HttpClient的get+post请求使用的更多相关文章
- HttpClient (POST GET PUT)请求
HttpClient (POST GET PUT)请求 package com.curender.web.server.http; import java.io.IOException; import ...
- HttpClient方式模拟http请求设置头
关于HttpClient方式模拟http请求,请求头以及其他参数的设置. 本文就暂时不给栗子了,当作简版参考手册吧. 发送请求是设置请求头:header HttpClient httpClient = ...
- HttpClient发送get post请求和数据解析
最近在跟app对接的时候有个业务是微信登录,在这里记录的不是如何一步步操作第三方的,因为是跟app对接,所以一部分代码不是由我写,我只负责处理数据,但是整个微信第三方的流程大致都差不多,app端说要传 ...
- HttpWebRequest 改为 HttpClient 踩坑记-请求头设置
HttpWebRequest 改为 HttpClient 踩坑记-请求头设置 Intro 这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebR ...
- 使用HttpClient发送Get/Post请求 你get了吗?
HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议 ...
- org.apache.httpcomponents httpclient 发起HTTP JSON请求
1. pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactI ...
- httpclient的几种请求URL的方式
一.httpclient项目有两种使用方式.一种是commons项目,这一个就只更新到3.1版本了.现在挪到了HttpComponents子项目下了,这里重点讲解HttpComponents下面的ht ...
- HttpClient发起Http/Https请求工具类
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...
- HttpClient方式模拟http请求
方式一:HttpClient import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.http.*; im ...
- Android HttpClient GET或者POST请求基本使用方法(转)
在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.这里只介绍如何使用HttpCl ...
随机推荐
- 【CF】509E Pretty Song
数学规律题,很容易计算的.以初始测试数据3为例.Str Y I S V O W E L--------------------------Len 1 2 3 4 | 5 6 7 8Y ...
- Unity 利用Coroutine实现跳动数字效果
纯粹转载:转载注明参考链接! 参考链接:http://xataxnova.blog.163.com/blog/static/236620063201451061738122/,作者:网易博客 xata ...
- bzoj3261
xor有一个很重要的性质就是A xor B xor B=A所以这道题求[l,r]中p,使a[p] xor a[p+1] xor ... xor a[N] xor x 最大就是=最大化a[1] xor ...
- BZOJ3687: 简单题
题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3687 小呆开始研究集合论了,他提出了关于一个数集四个问题: 1.子集的异或和的算术和. 2.子 ...
- [回顾]SVE回顾
SVE回顾 写完后的自评:书写太过凌乱,基本无法阅读. 前几日,SVE通过了TR5,虽说是一个小得不能再小的项目,即使到最后也存在一些未能解决的问题,但在用户的通融下还是在超期一段时间后写下了一个暂时 ...
- [QT]Qt+VS2012+Win8 64Bit安装
学习Qt鸟,当年没听@Coding_Peon(http://weibo.com/u/1764451551?topnav=1&wvr=5&topsug=1)话好好学习QT和Python之 ...
- 青云QingCloud业内率先支持云端全面透明代理功能 | SDNLAB | 专注网络创新技术
青云QingCloud业内率先支持云端全面透明代理功能 | SDNLAB | 专注网络创新技术 青云QingCloud业内率先支持云端全面透明代理功能
- 深入理解jvm之内存区域与内存溢出
文章目录 1. Java内存区域与内存溢出异常 1.1. 运行时数据区域 1.1.1. 程序计数器 1.1.2. java虚拟机栈 1.1.3. 本地方法栈 1.1.4. Java堆(Java Hea ...
- thinkphp I方法取传参
/** * 获取输入参数 支持过滤和默认值 * 使用方法: * <code> * I('id',0); 获取id参数 自动判断get或者post * I('post.name','','h ...
- Jenkins的plugin开发
Jenkins强大的功能主要靠其丰富的plugin体现,之前的一篇博客<Jenkins安装plugin>中介绍了如何找到并安装需要的plugin.虽然目前已经有大量非常优秀的plugin可 ...