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 ...
随机推荐
- once
var once = function(obj, evtType, handler) { var f = function() { //console.log(arguments) handler.a ...
- Light OJ 1036 - A Refining Company
题目大意: 一个m*n的矩阵,里面有两种矿物质铀和镭,现在要把铀和镭运送到指定位置.北边是炼镭厂,西边是了炼铀厂. 现在要建立传送带,传送带有两种,一种是从东到西,另一种是从南到北,传送带不能交叉,并 ...
- shell 执行jar 的命令
#!/bin/sh ############## #判断是否程序已启动 jappname='Test' mainclasspath="com.company.commontest.test& ...
- 2013.08.23.diary
Today, my baby called me.She said, she want to go abroad . And she wants me to go abroad too. I thin ...
- Python中AND-OR的用法
学习Python中的lambda函数的时候,才发现原来Python中的AND和OR还可以有一些别的用法.Python中的布尔逻辑计算的结果并非返回布尔值,而是返回它们相互之间的某一个.文章的部分例子来 ...
- 《University Calculus》-chaper13-多重积分-二重积分的计算
之前关于二重积分的笔记,介绍了二重积分概念的引入,但是对于它的计算方法(化为累次积分),介绍的较为模糊,它在<概率论基础教程>中一系列的推导中发挥着很重要的作用. 回想先前关于二重积分的几 ...
- Javascript诞生与历史
基本常识 Brendan Eich在1995年4月入职Netscape Communications Corporation(网景通信公司).并于1995年5月用10天时间发明了Javascript. ...
- dom0的cpu hotplug【续】
上一篇说到,手动xm vcpu-pin住,在hotplug就好了. 本质上,还是因为代码有bug,导致vcpu offline的时候,信息没有清理干净,有残留,当vcpu online的时候,如果调度 ...
- 【java/C# 服务器】IOS 配置推送证书 p12文件流程 - 勿以己悲
在配置 P12 证书文件之前, 我们要准备三个文件 1.PushChat.certSigningRequest 请求证书文件 2.PushChatKey.p12 ...
- SQL Server 2012 sa 用户登录 18456 错误
近期想研究下SQL SERVER2012 Enterprise版本号的数据库,听说功能非常强大. 我是在win7上安装的,安装的过程非常顺利,我在用"Windows 身份验证"时, ...