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 ... 
随机推荐
- 2015第45周五IE11实用开发工具摘录及设置IE缓存
			UI响应工具的作用 UI响应工具顾名思义就是查看UI响应时间的工具,通过这个工具可以帮助我们确定应用中的哪些组件占用了多少CPU时间,让我们之后可以更有针对性的进行优化,从而最大限度地改善应用性能,同 ... 
- Google Map API 学习三
- 数据结构(主席树):HZOI 2016 采花
			[题目描述] 给定一个长度为n,包含c种颜色的序列,有m个询问,每次给出两个数l,r,表示询问区间[l,r]中有多少种颜色的出现次数不少于2次. 本题强制在线,对输入的l,r进行了加密,解密方法为: ... 
- POJ1218
			Problem C Time Limit : 2000/1000ms (Java/Other) Memory Limit : 20000/10000K (Java/Other) Total Su ... 
- 在Windows Server 2012 上安装Exchange 2013 服务器
			前文:http://www.cnblogs.com/Liangw/archive/2011/09/19/2559944.html 安装准备: 1.加入一个存在的域(?如何建立一个域) 2.登录Wind ... 
- HTML---网页编程(2)
			前言 接着前面的HTML-网络编程1)来学习吧~~~ 色彩的表示 在计算机显示器中,使用红(red).绿(green).蓝(blue)3种颜色来构成各种各样的颜色.颜色的种类有16,256及65536 ... 
- POJ 1159  Palindrome   最长公共子序列的问题
			Description A palindrome is a symmetrical string, that is, a string read identically from left to ri ... 
- (java)    Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
			/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * Lis ... 
- ACM1230_火星A+B(进位的运算)
			//只要看懂火星A+B的进位关系就好了 #include<stdio.h> ]={,,,,,,,,,,,,,,,,,,,,,,,,,}; int main() { ],b[],sum[]; ... 
- hpuoj 问题 C: 善良的国王【最小生成树kurskal】
			问题 C: 善良的国王 时间限制: 1 Sec 内存限制: 128 MB提交: 112 解决: 48[提交][状态][讨论版] 题目描述 很久很久以前,有一个贫困的国家,这个国家有一个善良爱民的国 ... 
