import com.alibaba.nacos.common.utils.MapUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
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.entity.StringEntity;
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.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class HttpsClientUtil {
public final static int port = 443;
public final static String SEND_TYPE_JSON = "application/json;charset=UTF-8";
public final static String SEND_TYPE_XML = "application/xml;charset=UTF-8";
public final static String SEND_TYPE_TEXT = "text/xml;charset=UTF-8";
private static Logger logger = LoggerFactory.getLogger(HttpsClientUtil.class);
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
// 初始化https 不做身份验证
static {
try {
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(),
new String[] { "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register(HTTP, new PlainConnectionSocketFactory()).register(HTTPS, sslsf).build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);// max connection
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized static CloseableHttpClient getHttpClient() throws Exception {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm)
.setConnectionManagerShared(true).build();
return httpClient;
}
/**
* Post 请求
*
* @param url
* @param sendBody
* @param header
* @return
*/
public static String postForJson(String url, String sendBody, Map<String, String> header) {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求实体
StringEntity entity = new StringEntity(sendBody, "UTF-8");
entity.setContentType(
new BasicHeader(org.apache.http.protocol.HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
if (!StringUtils.isEmpty(entity)) {
httpPost.setEntity(entity);
}
logger.info(MessageFormat.format("Https Request URL: [{0}]", url));
logger.info(MessageFormat.format("Https Request Headers: [{0}]", header.entrySet()));
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity);
} else {
readHttpResponse(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
*
* @Description: Post 请求发送XML格式数据
* @Title: postForXML
* @param: @param url
* @param: @param sendBody
* @param: @param header
* @param: @return
* @return: String
* @throws
*/
public static String postForXML(String url, String sendBody, Map<String, String> header) {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求实体
StringEntity entity = new StringEntity(sendBody, "UTF-8");
entity.setContentType(new BasicHeader(org.apache.http.protocol.HTTP.CONTENT_TYPE, SEND_TYPE_XML));
if (!StringUtils.isEmpty(entity)) {
httpPost.setEntity(entity);
}
logger.info(MessageFormat.format("Https Request URL: [{0}]", url));
logger.info(MessageFormat.format("Https Request Headers: [{0}]", header.entrySet()));
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity, "UTF-8");
} else {
readHttpResponse(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* Put 请求
*
* @param url
* @param sendBody
* @param header
* @return
*/
public static String putForJson(String url, String sendBody, Map<String, String> header) {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpPut httpPut = new HttpPut(url);
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
}
}
// 设置请求实体
StringEntity entity = new StringEntity(sendBody, "UTF-8");
entity.setContentType(
new BasicHeader(org.apache.http.protocol.HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
if (!StringUtils.isEmpty(entity)) {
httpPut.setEntity(entity);
}
logger.info(MessageFormat.format("Https Request URL: [{0}]", url));
logger.info(MessageFormat.format("Https Request Headers: [{0}]", header.entrySet()));
HttpResponse response = httpClient.execute(httpPut);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity);
} else {
readHttpResponse(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* Get 请求
*
* @param url
* @param sendBody
* @param header
* @return
*/
public static String getForJson(String url, String sendBody, Map<String, String> header) {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
HttpGet httpGet = new HttpGet(url);
// 设置头信息
if (MapUtils.isNotEmpty(header)) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
logger.info(MessageFormat.format("Https Request URL: [{0}]", url));
logger.info(MessageFormat.format("Https Request Headers: [{0}]", header.entrySet()));
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity);
} else {
readHttpResponse(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* https 返回状态处理
*
* @param response
* @return
* @throws ParseException
* @throws IOException
*/
public static String readHttpResponse(HttpResponse response) throws ParseException, IOException {
StringBuilder builder = new StringBuilder();
HttpEntity entity = response.getEntity();
builder.append("status: " + response.getStatusLine());
builder.append("header: ");
HeaderIterator iterator = response.headerIterator();
while (iterator.hasNext()) {
builder.append("\t" + iterator.next());
}
if (!StringUtils.isEmpty(entity)) {
String result = EntityUtils.toString(entity);
builder.append("response length: " + result.length());
builder.append("response content: " + result.replace("\r\n", ""));
}
logger.info(MessageFormat.format("Https Response 返回状态结果: {0}", builder.toString()));
return builder.toString();
}
/**
*
* @Description: 获取request中的值
* @Title: getRequestHeader
* @param: @param request
* @param: @return
* @return: Map<String,String>
* @throws
*/
public static Map<String, String> getRequestHeader(HttpServletRequest request) {
Map<String, String> map = new HashMap<String, String>();
Enumeration<?> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
}
http工具类
最新推荐文章于 2024-01-23 16:14:11 发布