HttpClient 가 Http/Https 요청 도구 클래스 를 시작 합 니 다.
35988 단어 Commons.Utils
org.apache.httpcomponents
httpclient
4.5.1
4.5 버 전의 Httpclient 에 대해 연결 풀 방식 으로 연결 관리
package com.wx4jdemo.controller.utils;
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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
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.ssl.SSLContextBuilder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Https
*/
public class SSLClientCustom {
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslConnectionSocketFactory = null;
private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;//
private static SSLContextBuilder sslContextBuilder = null;// Https
static {
try {
sslContextBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
// true
return true;
}
});
sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry registryBuilder = RegistryBuilder.create()
.register(HTTP, new PlainConnectionSocketFactory())
.register(HTTPS, sslConnectionSocketFactory)
.build();
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registryBuilder);
poolingHttpClientConnectionManager.setMaxTotal(200);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
/**
*
*
* @return
* @throws Exception
*/
public static CloseableHttpClient getHttpClinet() throws Exception {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
.setConnectionManager(poolingHttpClientConnectionManager)
.setConnectionManagerShared(true)
.build();
return httpClient;
}
}
Registry 클래스 는 Http/Https 연결 을 등록 하고 https 연결 시 인증서 인증 을 건 너 뛰 며 모든 사이트 에 기본적으로 신뢰 합 니 다.
다음은 요청 한 도구 류 코드 작성 입 니 다.
package com.wx4jdemo.controller.utils;
import org.apache.commons.collections.MapUtils;
import org.apache.http.*;
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.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Http/Https
*/
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
/**
* post
*
* @param url:
* @param header:
* @param params: form
* @param httpEntity json/xml
* @return
*/
public static String doPostRequest(String url, Map, String> header, Map, String> params, HttpEntity httpEntity) {
String resultStr = "";
if (StringUtils.isEmpty(url)) {
return resultStr;
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = SSLClientCustom.getHttpClinet();
HttpPost httpPost = new HttpPost(url);
// header
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry, String> stringStringEntry : header.entrySet()) {
httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
}
}
//
if (MapUtils.isNotEmpty(params)) {
List paramList = new ArrayList<>();
for (Map.Entry, String> stringStringEntry : params.entrySet()) {
paramList.add(new BasicNameValuePair(stringStringEntry.getKey(), stringStringEntry.getValue()));
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
httpPost.setEntity(urlEncodedFormEntity);
}
//
if (httpEntity != null) {
httpPost.setEntity(httpEntity);
}
//
httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity httpResponseEntity = httpResponse.getEntity();
resultStr = EntityUtils.toString(httpResponseEntity);
logger.info(" , :{}, :{}", url, resultStr);
} else {
StringBuffer stringBuffer = new StringBuffer();
HeaderIterator headerIterator = httpResponse.headerIterator();
while (headerIterator.hasNext()) {
stringBuffer.append("\t" + headerIterator.next());
}
logger.info(" : :{}, :{}, :{}", url, httpResponse.getStatusLine().getStatusCode(), stringBuffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeConnection(httpClient, httpResponse);
}
return resultStr;
}
public static String doGetRequest(String url, Map, String> header, Map, String> params) {
String resultStr = "";
if (StringUtils.isEmpty(url)) {
return resultStr;
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
httpClient = SSLClientCustom.getHttpClinet();
//
if (MapUtils.isNotEmpty(params)) {
url = url + buildUrl(params);
}
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)//
.setConnectionRequestTimeout(5000)//
.setSocketTimeout(5000)//
.setRedirectsEnabled(true).build();//
httpGet.setConfig(requestConfig);
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry, String> stringStringEntry : header.entrySet()) {
httpGet.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
}
}
//
httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
resultStr = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
logger.info(" :{}, :{}", url, resultStr);
} else {
StringBuffer stringBuffer = new StringBuffer();
HeaderIterator headerIterator = httpResponse.headerIterator();
while (headerIterator.hasNext()) {
stringBuffer.append("\t" + headerIterator.next());
}
logger.info(" : :{}, :{}", httpResponse.getStatusLine().getStatusCode(), stringBuffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
HttpClientUtils.closeConnection(httpClient, httpResponse);
}
return resultStr;
}
/**
*
*/
private static void closeConnection(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* get
*
* @return
*/
private static String buildUrl(Map, String> map) {
if (MapUtils.isEmpty(map)) {
return "";
}
StringBuffer stringBuffer = new StringBuffer("?");
for (Map.Entry, String> stringStringEntry : map.entrySet()) {
stringBuffer.append(stringStringEntry.getKey()).append("=").append(stringStringEntry.getValue()).append("&");
}
String result = stringBuffer.toString();
if (StringUtils.isNotEmpty(result)) {
result = result.substring(0, result.length() - 1);// &
}
return result;
}
}
main 함수 테스트 쓰기
public static void main(String[] args) {
String httpsUrl = "https://github.com/";
HttpClientUtils.doGetRequest(httpsUrl, null, null);
String hpptsPostUrl = "https://www.cnblogs.com/Mr-Rocker/p/6229652.html";
HttpClientUtils.doPostRequest(hpptsPostUrl, null, null, null);
Map params = new HashMap<>();
params.put("ie", "utf-8");
params.put("wd", "java");
params.put("tn", "92032424_hao_pg");
Map header = new HashMap<>();
header.put("User-Agent:", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
HttpClientUtils.doGetRequest("https://www.baidu.com/s", header, params);
}
이 글 은 인터넷 사례 를 참고 하 는 토대 에서 작성 되 었 습 니 다.개인 학습 으로 만 저작권 침해 가 있 으 면 연락 하여 삭제 하 십시오.감사합니다.
--엔 딩 멘 트
、 , , ;
、 , , 。