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 ...
随机推荐
- 【HDOJ】1325 Is It A Tree?
并查集.需要考虑入度. #include <stdio.h> #include <string.h> #define MAXNUM 10005 int bin[MAXNUM]; ...
- BZOJ1609: [Usaco2008 Feb]Eating Together麻烦的聚餐
1609: [Usaco2008 Feb]Eating Together麻烦的聚餐 Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 938 Solved ...
- java基础(八) 面向对象(三)
这里有我之前上课总结的一些知识点以及代码大部分是老师讲的笔记 个人认为是非常好的,,也是比较经典的内容,真诚的希望这些对于那些想学习的人有所帮助! 由于代码是分模块的上传非常的不便.也比较多,讲的也是 ...
- codeforces 421d bug in code
题目链接:http://codeforces.com/problemset/problem/421/D 题目大意:每个人说出自己认为的背锅的两个人,最后大BOSS找两个人来背锅,要求至少符合p个人的想 ...
- 用redis实现支持优先级的消息队列
http://www.cnblogs.com/tianqiq/p/4309791.html http://www.cnblogs.com/it-cen/p/4312098.html http://ww ...
- GitHub上整理的一些资料(转)
技术站点 Hacker News:非常棒的针对编程的链接聚合网站 Programming reddit:同上 MSDN:微软相关的官方技术集中地,主要是文档类 infoq:企业级应用,关注软件开发领域 ...
- linux常用命令大全(转)
由于记忆力有限,把平时常用的Linux命令整理出来,以便随时查阅: linux 基本命令 ls (list 显示当前目录下文件和目录 ls -l 详细显示 =ll ) [root@linux ...
- intellij安装 配置 创建项目
使用intellij创建项目的整个过程如下: 首先,点击intllij的.exe文件,如果是第一次安装,选择第二个选项即可 Intellij需要license key,可以使用注册机生成相应的name ...
- webview 本地上传文件
参考http://blog.csdn.net/zhtsuc/article/details/49154099 直接上代码 public class MainActivity1 extends Ac ...
- [转]Android中dp,px,sp概念梳理以及如何做到屏幕适配
http://blog.csdn.net/jiangwei0910410003/article/details/40509571 今天又开始我的App开发,因为之前一直做的是SDK,所以涉及到界面UI ...