博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http请求pom 客户端_org.apache.http.client.HttpClient使用方法
阅读量:30585 次
发布时间:2020-01-05

本文共 5187 字,大约阅读时间需要 17 分钟。

packagecom.feilong.reptile.util;importjava.io.IOException;importjava.io.InterruptedIOException;importjava.net.UnknownHostException;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjava.util.Map.Entry;importjavax.net.ssl.SSLException;importorg.apache.commons.codec.Charsets;importorg.apache.http.Header;importorg.apache.http.HttpEntityEnclosingRequest;importorg.apache.http.HttpRequest;importorg.apache.http.HttpResponse;importorg.apache.http.client.HttpClient;importorg.apache.http.client.HttpRequestRetryHandler;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.client.protocol.HttpClientContext;importorg.apache.http.client.utils.URIBuilder;importorg.apache.http.config.SocketConfig;importorg.apache.http.conn.ConnectTimeoutException;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.impl.conn.PoolingHttpClientConnectionManager;importorg.apache.http.protocol.HttpContext;importorg.apache.http.util.EntityUtils;/*** 使用HttpClient发送和接收Http请求

*

*@authormanzhizhen

**/

public classHttpUtils {private staticHttpClient httpClient;//最大连接数

private static final int MAX_CONNECTION = 100;//每个route能使用的最大连接数,一般和MAX_CONNECTION取值一样

private static final int MAX_CONCURRENT_CONNECTIONS = 100;//建立连接的超时时间,单位毫秒

private static final int CONNECTION_TIME_OUT = 1000;//请求超时时间,单位毫秒

private static final int REQUEST_TIME_OUT = 1000;//最大失败重试次数

private static final int MAX_FAIL_RETRY_COUNT = 3;//请求配置,可以复用

private staticRequestConfig requestConfig;static{

SocketConfig socketConfig=SocketConfig.custom()

.setSoTimeout(REQUEST_TIME_OUT).setSoKeepAlive(true)

.setTcpNoDelay(true).build();

requestConfig=RequestConfig.custom()

.setSocketTimeout(REQUEST_TIME_OUT)

.setConnectTimeout(CONNECTION_TIME_OUT).build();/*** 每个默认的 ClientConnectionPoolManager 实现将给每个route创建不超过2个并发连接,最多20个连接总数。*/PoolingHttpClientConnectionManager connManager= newPoolingHttpClientConnectionManager();

connManager.setMaxTotal(MAX_CONNECTION);

connManager.setDefaultMaxPerRoute(MAX_CONCURRENT_CONNECTIONS);

connManager.setDefaultSocketConfig(socketConfig);

httpClient=HttpClients.custom().setConnectionManager(connManager)//添加重试处理器

.setRetryHandler(newMyHttpRequestRetryHandler()).build();

}public static voidmain(String[] args) {

testGet();

}/*** 测试get方法*/

private static voidtestGet() {

String url= "http://restapi.amap.com/v3/place/text";

Map paramMap = new HashMap();

paramMap.put("key", "95708f902ac2428ea119ec99fb70e6a3");

paramMap.put("keywords", "互联网金融大厦");

paramMap.put("city", "330100");

paramMap.put("extensions", "all");try{

System.out.println(get(url, paramMap));

}catch(Exception e) {

e.printStackTrace();

}

}/*** post请求

*

*@paramurl

*@paramparamMap

*@paramheaders

*@return*@throwsException*/

public static String post(String url, MapparamMap,

List headers) throwsException {

URIBuilder uriBuilder= newURIBuilder(url);if (paramMap != null) {//添加请求参数

for (Entryentry : paramMap.entrySet()) {

uriBuilder.addParameter(entry.getKey(), entry.getValue());

}

}

HttpPost httpPost= newHttpPost(uriBuilder.build());if (headers != null) {//添加请求首部

for(Header header : headers) {

httpPost.addHeader(header);

}

}

httpPost.setConfig(requestConfig);//执行请求

HttpResponse response =httpClient.execute(httpPost);returnEntityUtils.toString(response.getEntity(), Charsets.UTF_8);

}/*** post请求,不带请求首部

*

*@paramurl

*@paramparamMap

*@return*@throwsException*/

public static String post(String url, MapparamMap)throwsException {return post(url, paramMap, null);

}/*** get请求

*

*@paramurl

*@paramparamMap

*@paramheaders

*@return*@throwsException*/

public static String get(String url, MapparamMap,

List headers) throwsException {

URIBuilder uriBuilder= newURIBuilder(url);if (paramMap != null) {//添加请求参数

for (Entryentry : paramMap.entrySet()) {

uriBuilder.addParameter(entry.getKey(), entry.getValue());

}

}

HttpGet httpGet= newHttpGet(uriBuilder.build());if (headers != null) {//添加请求首部

for(Header header : headers) {

httpGet.addHeader(header);

}

}

httpGet.setConfig(requestConfig);//执行请求

HttpResponse response =httpClient.execute(httpGet);returnEntityUtils.toString(response.getEntity(), Charsets.UTF_8);

}/*** get请求,不带请求首部

*

*@paramurl

*@paramparamMap

*@return*@throwsException*/

public static String get(String url, MapparamMap)throwsException {return get(url, paramMap, null);

}/*** 请求重试处理器

*@authormanzhizhen

**/

private static class MyHttpRequestRetryHandler implementsHttpRequestRetryHandler {

@Overridepublic boolean retryRequest(IOException exception, intexecutionCount,

HttpContext context) {if (executionCount >=MAX_FAIL_RETRY_COUNT) {return false;

}if (exception instanceofInterruptedIOException) {//超时

return false;

}if (exception instanceofUnknownHostException) {//未知主机

return false;

}if (exception instanceofConnectTimeoutException) {//连接被拒绝

return false;

}if (exception instanceofSSLException) {//SSL handshake exception

return false;

}

HttpClientContext clientContext=HttpClientContext.adapt(context);

HttpRequest request=clientContext.getRequest();boolean idempotent = !(request instanceofHttpEntityEnclosingRequest);if(idempotent) {//如果请求被认为是幂等的,则重试

return true;

}return false;

}

}

}

转载地址:http://umzsdu.baihongyu.com/

你可能感兴趣的文章
说说如何使用 Android 的本地广播
查看>>
说说在 Android 中如何实现强制下线功能
查看>>
说说 jBPM 流程定义语言(8)—— sub-process(子流程活动)
查看>>
说说 MD5 加密后的类型(16位与 32位的区别)
查看>>
Android Studio 中出现 java.net.SocketException “Socket closed” 问题的解决方法
查看>>
在 Android Device Monitor 的 File Explorer 中,无法打开某些文件夹的解决方法
查看>>
Android Device Monitor 报 open failed: Permission denied 问题的解决方法
查看>>
说说如何使用 Java 原生方法实现 MD5 加密算法
查看>>
说说在 Spring 中如何创建增强类(AOP)
查看>>
Vue 教程(8)—— 事件处理
查看>>
Vue 教程(9)—— 表单输入绑定
查看>>
说说 Android 中 WebView 的基本用法
查看>>
SWIFT入门 Dictionary
查看>>
SWIFT SET
查看>>
swift operation
查看>>
利用NVIDIA TensorRT加速交通环境感知之亲测有效
查看>>
NVIDIA 第三届Sky Hackathon学深会踩坑实录~
查看>>
关于linkedin的network的观察和自己的职业道路的追求
查看>>
生死6小时!!!!!!!!!!!!!!!!1
查看>>
LSE的拒信
查看>>