HttpUtils JAVA


package iih.custom.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.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.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
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 iih.custom.common.log.CustomBizLogger;

/**
* httpclient 工具類
* @author tian.hq 2019.05.31
*
*/
public class HttpUtils {
private static final int timeOut = 100 * 1000;

/**
* 創建httpClient 對象
* @param ip
* @param port
* @return
*/
public static HttpClient getHttpClient(String ip,Integer port) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
// 將最大連接數增加
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(200);
HttpHost httpHost = new HttpHost(ip, port);
// 將目標主機的最大連接數增加
cm.setMaxPerRoute(new HttpRoute(httpHost), 200);
HttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
// 設置重試次數
.setRetryHandler(new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount > 3) {
CustomBizLogger.info("Maximum tries reached for client http pool");
return false;
}
// 服務器端沒有返回的情況,一般是連接池里面的連接失效,需要重試
if (exception instanceof org.apache.http.NoHttpResponseException) {
CustomBizLogger.info("No response from server on " + executionCount + " call");
return true;
}
if (exception instanceof java.net.SocketException) {
// 客戶端主動關閉連接的情況,一般是連接池里面的連接失效,需要重試
if (exception.getMessage().indexOf("Connection reset") >= 0) {
CustomBizLogger.info("java.net.SocketException Connection reset " + executionCount + " call");
return true;
}
}
if (exception instanceof java.net.SocketTimeoutException) {
// 連接或者響應超時,需要重試
CustomBizLogger.info("java.net.SocketTimeoutException: Read timed out " + executionCount + " call");
return true;
}
return false;
}
})
.build();
return httpClient;
}

private static Registry<ConnectionSocketFactory> getDefaultRegistry() {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
}

/**
* httpClient 發送post請求
* @param client
* @param url
* @param params
* @return 返回
* @throws Exception
*/
public static String sendPost(HttpClient client,String url,Map<String,Object> params) throws Exception {
HttpPost httppost = new HttpPost(url);
config(httppost);
setPostParams(httppost, params);
HttpResponse response = null;
try {
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
CustomBizLogger.error("httpClient 發送post請求異常",e);
throw e;
}
}

public static String sendPost(HttpClient client,String url,String data) throws Exception {
HttpPost httppost = new HttpPost(url);
config(httppost);
StringEntity stringEntity = new StringEntity(data,Charset.forName("UTF-8"));
httppost.setEntity(stringEntity);
HttpResponse response = null;
try {
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
CustomBizLogger.error("httpClient 發送post請求異常",e);
throw e;
}
}

/***
* 發送post 請求 ,附帶header信息
* @param client
* @param url
* @param data
* @param headers
* @return
* @throws Exception
*/
public static String sendPost(HttpClient client,String url,String data,Map<String,String> headers) throws Exception {
HttpPost httppost = new HttpPost(url);
config(httppost);
fillHttpPostHeader(httppost,headers);
StringEntity stringEntity = new StringEntity(data,Charset.forName("UTF-8"));
httppost.setEntity(stringEntity);
HttpResponse response = null;
try {
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return result;
} catch (Exception e) {
CustomBizLogger.error("httpClient 發送post請求異常",e);
throw e;
}
}

private static void setPostParams(HttpPost httpost, Map<String, Object> params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
CustomBizLogger.error("設置http post 參數異常",e);
}
}

private static void config(HttpRequestBase httpRequestBase) {
// 配置請求的超時設置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(timeOut)
.setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpRequestBase.setConfig(requestConfig);
}

/**
* 為HttpPost添加header信息
* @param post
* @param headers
*/
private static void fillHttpPostHeader(HttpPost post,Map<String,String> headers){
if(headers == null){
return ;
}
for(String key:headers.keySet()){
post.addHeader(key, headers.get(key));
}
}


}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM