博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
httpClient4.* 使用教程
阅读量:6912 次
发布时间:2019-06-27

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

hot3.png

httpclient 4.*工具类 拿过去直接用,已经测试过,性能没问题。有需要重载方法的 可以直接增加。

 

有什么问题的 直接在下面评论,第一时间回复。

 

import com.qbao.pay.engine.codec.Digest;import com.qbao.pay.engine.codec.RSAUtil;import com.qbao.pay.engine.tools.BeanConvertUtil;import com.qianbao.baoxian.external.entity.payengine.request.MerchantApiPayRequest;import com.qianbao.baoxian.external.entity.payengine.request.PersonalApiPayRequest;import org.apache.http.*;import org.apache.http.client.HttpRequestRetryHandler;import org.apache.http.client.config.RequestConfig;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.protocol.HttpClientContext;import org.apache.http.config.Registry;import org.apache.http.config.RegistryBuilder;import org.apache.http.conn.ConnectTimeoutException;import org.apache.http.conn.socket.ConnectionSocketFactory;import org.apache.http.conn.socket.LayeredConnectionSocketFactory;import org.apache.http.conn.socket.PlainConnectionSocketFactory;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HttpContext;import org.apache.http.util.EntityUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.net.ssl.SSLException;import javax.net.ssl.SSLHandshakeException;import java.io.IOException;import java.io.InterruptedIOException;import java.net.URLEncoder;import java.net.UnknownHostException;import java.util.*;/** * Created by young on 16/9/6. */public class HttpConnectUtil {    private static final Logger LOGGER = LoggerFactory.getLogger(HttpConnectUtil.class);    private HttpConnectUtil() {    }    // 设置全局属性    private static final int CONNECTION_REQUEST_TIMEOUT = Integer.valueOf("60000");    private static final int SOCKET_TIMEOUT = Integer.valueOf("60000");    private static final int CONNECTION_TIMEOUT = Integer.valueOf("6000");    // 每台主机分配的连接数字    private static final int DEFAULT_MAX_PER_ROUTE = Integer.parseInt("500");    // 该值就是连接不够用的时候等待超时时间,一定要设置,而且不能太大    private static final int CONN_MANAGER_TIMEOUT = Integer.parseInt("500");    // 请求错误次数  到达了多少次就放弃    private static final int REQUEST_RETRY_COUNT = Integer.parseInt("1");    // http 连接方式    private static final String HTTP_MODE = "http";    // https 连接方式    private static final String HTTPS_MODE = "https";    /**     * 获取 CloseableHttpClient     * 

* 编辑时间 2016年09月06日14:18:34 *

* 编辑人 杨中仁 */ public static CloseableHttpClient getCloseableHttpClient() { ConnectionSocketFactory connectionSocketFactory = PlainConnectionSocketFactory .getSocketFactory(); LayeredConnectionSocketFactory layeredConnectionSocketFactory = SSLConnectionSocketFactory .getSocketFactory(); Registry

registry = RegistryBuilder .
create().register(HTTP_MODE, connectionSocketFactory) .register(HTTPS_MODE, layeredConnectionSocketFactory).build(); // 设置 连接池的最大连接 PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE); poolingHttpClientConnectionManager.setMaxTotal(CONN_MANAGER_TIMEOUT); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) { // 如果达到了请求错误次数 就不在请求 if (i >= REQUEST_RETRY_COUNT) { LOGGER.info("[HttpConnectUtil getCloseableHttpClient] init closeableHttpClient: 请求次数为:{} ", i); return false; } // 处理异常 if (e instanceof NoHttpResponseException) { // 如果服务器丢掉了连接,那么就重试 LOGGER.error("[HttpConnectUtil getCloseableHttpClient] init closeableHttpClient: 服务器丢掉了连接 请求异常为:{} ", e.getMessage()); return true; } if (e instanceof SSLHandshakeException || e instanceof SSLException) { // 不要重试SSL握手异常 LOGGER.error("[HttpConnectUtil getCloseableHttpClient] init closeableHttpClient: SSL异常 请求异常为:{} ", e.getMessage()); return false; } if (e instanceof InterruptedIOException) { // 超时不在处理 LOGGER.error("[HttpConnectUtil getCloseableHttpClient] init closeableHttpClient: 超时 请求异常为:{} ", e.getMessage()); return false; } if (e instanceof UnknownHostException) { // 目标服务器不可达 不在处理 LOGGER.error("[HttpConnectUtil getCloseableHttpClient] init closeableHttpClient: 目标服务器不可达 请求异常为:{} ", e.getMessage()); return false; } if (e instanceof ConnectTimeoutException) { // 连接被拒绝 不在处理 LOGGER.error("[HttpConnectUtil getCloseableHttpClient] init closeableHttpClient: 连接被拒绝 请求异常为:{} ", e.getMessage()); return false; } HttpClientContext httpClientContext = HttpClientContext .adapt(httpContext); HttpRequest request = httpClientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; // 请求配置 连接超时时间 RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(CONNECTION_TIMEOUT).build(); // 设置 closeableHttpClient CloseableHttpClient closeableHttpClient = HttpClients.custom() .setDefaultRequestConfig(requestConfig).setRetryHandler(httpRequestRetryHandler).build(); return closeableHttpClient; } /** * http get 请求做处理 编码格式 UTF-8 *

* 编辑时间 2016年09月07日15:21:55 *

* 编辑人 杨中仁 */ public static String sendGetRequest(String requestURL, List

basicNameValuePairs) throws IOException { String responseContent = null; // 初始化一下返回内容 CloseableHttpClient closeableHttpClient = getCloseableHttpClient(); // 获取 CloseableHttpClient CloseableHttpResponse closeableHttpResponse; // 初始化 HttpResponse HttpEntity httpEntity; // 初始化 HttpEntity String parameterURL = requesturiMode(basicNameValuePairs); HttpGet httpGet = new HttpGet(requestURL + parameterURL); try { long beginTime = System.currentTimeMillis(); closeableHttpResponse = closeableHttpClient.execute(httpGet); long endTime = System.currentTimeMillis(); // 执行完成 打在log下面 httpResponse code if (closeableHttpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { // 如果状态是 200 httpGet.abort(); LOGGER.error("[HttpClientUtil sendGetRequest] error, url : {} , params : {}, status :{}", requestURL, basicNameValuePairs, closeableHttpResponse.getStatusLine().getStatusCode()); return "ERROR" + closeableHttpResponse.getStatusLine().getStatusCode(); } httpEntity = closeableHttpResponse.getEntity(); try { if (httpEntity != null) { responseContent = EntityUtils.toString(httpEntity, Consts.UTF_8); } } finally { if (httpEntity != null) { httpEntity.getContent().close(); EntityUtils.consume(httpEntity); } } if (closeableHttpResponse!=null){ closeableHttpResponse.close(); } LOGGER.info("[HttpClientUtil sendPostRequest] Debug url:{} , response string :{},time={}ms", requestURL, responseContent, endTime - beginTime); } catch (IOException e) { LOGGER.error("与[" + requestURL + "]通信过程中发生异常,堆栈信息如下 {}", e); throw new IOException("与[" + requestURL + "]通信过程中发生异常,堆栈信息如下 {} ", e); } finally { // 关闭 try { closeableHttpClient.close(); httpGet.releaseConnection(); } catch (IOException e) { LOGGER.error("与[" + requestURL + "]通信过程中 关闭连接异常 ,堆栈信息如下 {}", e); throw new IOException("与[" + requestURL + "]通信过程中 关闭连接异常 ,堆栈信息如下 {} ", e); } finally { httpGet.releaseConnection(); } } return responseContent; } public static String requesturiMode(List
basicNameValuePairs) { StringBuffer result = new StringBuffer(); int index = 0; if (basicNameValuePairs != null && basicNameValuePairs.size() != 0) { for (BasicNameValuePair basicNameValuePair : basicNameValuePairs) { if (index == 0) { result.append("?"); } else { result.append("&"); } result.append(basicNameValuePair.getName() + "=" + basicNameValuePair.getValue()); index++; } } return result.toString(); } public static String requesturiMode(Map
basicNameValueMap) { StringBuffer result = new StringBuffer(); int index = 0; if (basicNameValueMap != null && basicNameValueMap.size() != 0) { Set
keySet = basicNameValueMap.keySet(); for (String key : keySet) { if (index == 0) { result.append("?"); } else { result.append("&"); } result.append(key + "=" + basicNameValueMap.get(key)); index++; } } return result.toString(); } /** * 使用 map 做参数 去 null 2016年09月20日10:15:59 * * @param requestURL 请求url host * @param basicNameValueMap 参数map * @return * @throws IOException 抛出io异常 */ public static String sendGetRequest(String requestURL, Map
basicNameValueMap) throws IOException { List
basicNameValuePairs = new ArrayList
(); // 转换一下map 给list if (basicNameValueMap != null && basicNameValueMap.size() > 0) { Set
keySet = basicNameValueMap.keySet(); BasicNameValuePair basicNameValuePair; for (String key : keySet) { basicNameValuePair = new BasicNameValuePair(key, basicNameValueMap.get(key)); basicNameValuePairs.add(basicNameValuePair); } } return sendGetRequest(requestURL, basicNameValuePairs); } public static String sendPostRequest(String requestURL, Map
basicNameValueMap) throws IOException { List
basicNameValuePairs = new ArrayList
(); // 转换一下map 给list if (basicNameValueMap != null && basicNameValueMap.size() > 0) { Set
keySet = basicNameValueMap.keySet(); BasicNameValuePair basicNameValuePair; for (String key : keySet) { basicNameValuePair = new BasicNameValuePair(key, basicNameValueMap.get(key)); basicNameValuePairs.add(basicNameValuePair); } } return sendPostRequest(requestURL, basicNameValuePairs); } /** * http post 请求做处理 编码格式 UTF-8 *

* 编辑时间 2016年09月07日15:19:54 *

* 编辑人 杨中仁 * * @param requestURL 主机地址 * @param basicNameValuePairs 参数集合 * @return 返回请求过来的文本内容 */ public static String sendPostRequest(String requestURL, List

basicNameValuePairs) throws IOException { String responseContent = null; // 初始化一下返回内容 CloseableHttpClient closeableHttpClient = getCloseableHttpClient(); // 获取 CloseableHttpClient CloseableHttpResponse closeableHttpResponse; // 初始化 HttpResponse HttpEntity httpEntity; // 初始化 HttpEntity HttpPost httpPost = new HttpPost(requestURL); try { if (basicNameValuePairs != null && basicNameValuePairs.size() != 0){ httpPost.setEntity(new UrlEncodedFormEntity(basicNameValuePairs,Consts.UTF_8)); } long beginTime = System.currentTimeMillis(); closeableHttpResponse = closeableHttpClient.execute(httpPost); long endTime = System.currentTimeMillis(); // 执行完成 打在log下面 httpResponse code if (closeableHttpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { // 如果状态是 200 httpPost.abort(); LOGGER.error("[HttpClientUtil sendPostRequest] error, url : {} , params : {}, status :{}", requestURL, basicNameValuePairs, closeableHttpResponse.getStatusLine().getStatusCode()); return "ERROR" + closeableHttpResponse.getStatusLine().getStatusCode(); } httpEntity = closeableHttpResponse.getEntity(); try { if (httpEntity != null) { responseContent = EntityUtils.toString(httpEntity, Consts.UTF_8); } } finally { if (httpEntity != null) { httpEntity.getContent().close(); EntityUtils.consume(httpEntity); } } if (closeableHttpResponse!=null){ closeableHttpResponse.close(); } LOGGER.info("[HttpClientUtil sendPostRequest] Debug url:{} , response string :{},time={}ms", requestURL, responseContent, endTime - beginTime); } catch (IOException e) { LOGGER.error("与[" + requestURL + "]通信过程中发生异常,堆栈信息如下 {}", e); throw new IOException("与[" + requestURL + "]通信过程中发生异常,堆栈信息如下 {} ", e); } finally { // 关闭 try { closeableHttpClient.close(); httpPost.releaseConnection(); } catch (IOException e) { LOGGER.error("与[" + requestURL + "]通信过程中 关闭连接异常 ,堆栈信息如下 {}", e); throw new IOException("与[" + requestURL + "]通信过程中 关闭连接异常 ,堆栈信息如下 {} ", e); } finally { httpPost.releaseConnection(); } } return responseContent; }}

 

转载于:https://my.oschina.net/superman158/blog/750812

你可能感兴趣的文章
企业营业执照OCR识别
查看>>
给图片加水印
查看>>
我的友情链接
查看>>
AIX系统中适用于ksh的循环语句
查看>>
Nginx 配置详解
查看>>
什么是ARP攻击及ARP欺骗的种类
查看>>
MAC 安装cocoapods 遇到问题
查看>>
abstract class和interface有什么区别?
查看>>
OneNMP路由器、交换机监控
查看>>
软件生命周期
查看>>
解决:安装Jenkins时web界面出现jenkins实例似乎已离线问题
查看>>
解决phpMyAdmin在nginx+php-fpm模式下无法使用的问题
查看>>
自动领豆golang版
查看>>
EditText 只能输入数字字母
查看>>
vue中的条件渲染
查看>>
lnmp搭建
查看>>
菜鸟学Linux 第063篇笔记 postfix+mysql+courier-authlib
查看>>
【 58沈剑 架构师之路】InnoDB七种锁——共享/排它锁、意向锁、插入意向锁
查看>>
终究未能留下,秦致被动离去,汽车之家已变天
查看>>
wxWidgets第一课 wx/wx.h解决头文件包含问题
查看>>