import org.apache.commons.collections.MapUtils;
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.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* Http请求工具类,支持xml和json格式请求
*/
public class HttpUtils {
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(HttpUtils.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 body
* @param header
* @return
*/
public static String postForJson(String url, String body, 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(body, "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);
}
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;
}
/**
* @throws
* @Description: Post 请求发送XML格式数据
* @Title: postForXML
* @param: @param url
* @param: @param body
* @param: @param header
* @param: @return
* @return: String
*/
public static String postForXML(String url, String body, 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(body, "UTF-8");
entity.setContentType(new BasicHeader(org.apache.http.protocol.HTTP.CONTENT_TYPE, SEND_TYPE_XML));
if (!StringUtils.isEmpty(entity)) {
httpPost.setEntity(entity);
}
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 body
* @param header
* @return
*/
public static String putForJson(String url, String body, 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(body, "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);
}
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 body
* @param header
* @return
*/
public static String getForJson(String url, String body, 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());
}
}
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", ""));
}
return builder.toString();
}
/**
* @throws
* @Description: 获取request中的值
* @Title: getRequestHeader
* @param: @param request
* @param: @return
* @return: Map<String, String>
*/
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工具类
于 2022-06-15 16:51:38 首次发布