HttpClient 연결 풀 설정 및 사용
11935 단어 HttpClient연결 탱크 설정 및 사용
package
com.mygame.common.utils;
import
java.io.IOException;
import
java.security.KeyManagementException;
import
java.security.KeyStoreException;
import
java.security.NoSuchAlgorithmException;
import
org.apache.http.Header;
import
org.apache.http.HttpStatus;
import
org.apache.http.client.config.RequestConfig;
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.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.conn.ssl.SSLConnectionSocketFactory;
import
org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import
org.apache.http.entity.StringEntity;
import
org.apache.http.impl.client.CloseableHttpClient;
import
org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import
org.apache.http.impl.client.HttpClients;
import
org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import
org.apache.http.ssl.SSLContextBuilder;
import
org.apache.http.util.EntityUtils;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
com.alibaba.fastjson.JSON;
public
class
GameHttpClient {
private
static
Logger logger = LoggerFactory.getLogger(GameHttpClient.
class
);
//
private
static
PoolingHttpClientConnectionManager poolConnManager =
null
;
private
static
CloseableHttpClient httpClient;
// , http
static
{
try
{
System.out.println(
" HttpClientTest~~~ "
);
SSLContextBuilder builder =
new
SSLContextBuilder();
builder.loadTrustMaterial(
null
,
new
TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf =
new
SSLConnectionSocketFactory(builder.build());
// HTTP HTPPS
Registry socketFactoryRegistry = RegistryBuilder.create().register(
"http"
, PlainConnectionSocketFactory.getSocketFactory()).register(
"https"
, sslsf).build();
//
poolConnManager =
new
PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolConnManager.setMaxTotal(
640
);
//
//
poolConnManager.setDefaultMaxPerRoute(
320
);
// MaxtTotal DefaultMaxPerRoute :
// 1、MaxtTotal ;
// 2、DefaultMaxPerRoute MaxTotal ; :
// MaxtTotal=400 DefaultMaxPerRoute=200
// http://www.abc.com , 200; 400;
// http://www.bac.com
// http://www.ccd.com , 200; 400( 400); DefaultMaxPerRoute
// httpClient
httpClient = getConnection();
System.out.println(
" HttpClientTest~~~ "
);
}
catch
(NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch
(KeyStoreException e) {
e.printStackTrace();
}
catch
(KeyManagementException e) {
e.printStackTrace();
}
}
public
static
CloseableHttpClient getConnection() {
RequestConfig config = RequestConfig.custom().setConnectTimeout(
5000
).setConnectionRequestTimeout(
5000
).setSocketTimeout(
5000
).build();
CloseableHttpClient httpClient = HttpClients.custom()
//
.setConnectionManager(poolConnManager)
.setDefaultRequestConfig(config)
//
.setRetryHandler(
new
DefaultHttpRequestRetryHandler(
2
,
false
)).build();
return
httpClient;
}
public
static
String httpGet(String url) {
HttpGet httpGet =
new
HttpGet(url);
CloseableHttpResponse response =
null
;
try
{
response = httpClient.execute(httpGet);
String result = EntityUtils.toString(response.getEntity());
int
code = response.getStatusLine().getStatusCode();
if
(code == HttpStatus.SC_OK) {
return
result;
}
else
{
logger.error(
" {} :{},{}"
, url, code,result);
return
null
;
}
}
catch
(IOException e) {
logger.error(
"http ,{}"
,url,e);
}
finally
{
try
{
if
(response !=
null
)
response.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
return
null
;
}
public
static
String post(String uri, Object params, Header... heads) {
HttpPost httpPost =
new
HttpPost(uri);
CloseableHttpResponse response =
null
;
try
{
StringEntity paramEntity =
new
StringEntity(JSON.toJSONString(params));
paramEntity.setContentEncoding(
"UTF-8"
);
paramEntity.setContentType(
"application/json"
);
httpPost.setEntity(paramEntity);
if
(heads !=
null
) {
httpPost.setHeaders(heads);
}
response = httpClient.execute(httpPost);
int
code = response.getStatusLine().getStatusCode();
String result = EntityUtils.toString(response.getEntity());
if
(code == HttpStatus.SC_OK) {
return
result;
}
else
{
logger.error(
" {} :{}, :{},{}"
, uri, code, params,result);
return
null
;
}
}
catch
(IOException e) {
logger.error(
" http "
, e);
}
finally
{
try
{
if
(response !=
null
) {
response.close();
}
}
catch
(IOException e) {
e.printStackTrace();
}
}
return
null
;
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
HttpClient에서 웹 페이지를 캡처하는 두 가지 방법1. NodeFilter를 이용하여 웹 페이지를 분석한다. 1. Parser a를 생성한다. url을 통해 인터넷의 웹 페이지 b를 추출한다. 로컬 웹 파일을 추출하여 파일을 읽고 웹 파일을 문자열로 전환한다. 2....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.