weaver-hrm-salary/src/com/engine/salary/util/HttpUtil.java

250 lines
9.6 KiB
Java
Raw Normal View History

2023-07-17 15:06:42 +08:00
package com.engine.salary.util;
import com.engine.salary.entity.taxagent.response.SzyhResponseHead;
import com.engine.salary.entity.taxpayment.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
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.ConnectTimeoutException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
/**
* Http调用处理类
*
* @author Terry
*/
@Slf4j
public class HttpUtil {
public static final String TEXT_TYPE = "text/plain";
public static final String JSON_TYPE = "application/json";
public static final String XML_TYPE = "text/xml";
public static final String HTML_TYPE = "text/html";
public static final String EXCEL_TYPE = "application/vnd.ms-excel";
public static final String STREAM_TYPE = "application/octet-stream";
public static final int SLEEP_TIME = 1000;
public static final int IAS_SUCCESS = 400;
public static HttpClient httpsTrustClient() {
try {
// 在调用SSL之前需要重写验证方法取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory socketFactory =
new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig =
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(Boolean.TRUE)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
// 创建ConnectionManager添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager(socketFactoryRegistry);
return HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
} catch (KeyManagementException | NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
/**
* 获取 HttpClient
*
* @param path
* @return
*/
public static HttpClient wrapClient(String path) {
HttpClient httpClient = HttpClientBuilder.create().build();
if (path != null && path.startsWith("https://")) {
return httpsTrustClient();
}
return httpClient;
}
/**
* 设置http超时时间
*
* @param requestConfig
* @return
*/
private static RequestConfig setTimeOutConfig(RequestConfig requestConfig) {
if (requestConfig == null) {
requestConfig = RequestConfig.DEFAULT;
}
return RequestConfig.copy(requestConfig).setConnectionRequestTimeout(900000).setConnectTimeout(900000)
.setSocketTimeout(900000).build();
}
/**
* get 请求
*
* @param url
* @param header
* @param params
* @return
*/
public static String getRequest(String url, Map<String, String> header, Map<String, String> params) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
StringBuilder urlStr = new StringBuilder();
urlStr.append(url).append("?");
int i = params.size();
for (Map.Entry<String, String> map : params.entrySet()) {
urlStr.append(map.getKey()).append("=").append(map.getValue());
if ((--i) == 0) {
continue;
}
urlStr.append("&");
}
try {
httpClient = (CloseableHttpClient) wrapClient(url);
HttpGet httpGet = new HttpGet(urlStr.toString());
if (null != header && !header.isEmpty()) {
for (String key : header.keySet()) {
httpGet.setHeader(key, header.get(key));
}
}
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000)
.setConnectionRequestTimeout(20000).setSocketTimeout(40000).build();
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
httpGet.abort();
EntityUtils.consume(entity);
} catch (IOException e) {
log.error("发起GET请求失败", e);
result = getTimeoutErrorResponse(result, e);
} finally {
if (null != response) {
try {
httpClient.close();
response.close();
} catch (IOException e) {
log.error("发起GET请求失败", e);
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
log.error("发起GET请求失败", e);
}
}
}
return result;
}
/**
* HTTP Post 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param header 编码格式
* @return 页面内容
*/
public static String doPost(String url, Map<String, String> header, String params, String contentType) {
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "close");
httpPost.setConfig(setTimeOutConfig(httpPost.getConfig()));
httpPost.setHeader("Content-Type", contentType);
if (null != header && !header.isEmpty()) {
for (String key : header.keySet()) {
httpPost.setHeader(key, header.get(key));
}
}
if (null != params) {
httpPost.setEntity(new StringEntity(params, Consts.UTF_8));
}
HttpClient httpClient = wrapClient(url);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
EntityUtils.consume(entity);
httpPost.abort();
return result;
} catch (Exception e) {
log.error("发起POST请求失败", e);
result = getTimeoutErrorResponse(result, e);
}
return result;
}
private static String getTimeoutErrorResponse(String result, Exception e) {
if (e instanceof ConnectTimeoutException) {
BaseResponse baseResponse = new BaseResponse();
SzyhResponseHead head = new SzyhResponseHead();
head.setCode("-1");
head.setMsg(SalaryI18nUtil.getI18nLabel(184072, "抱歉,系统因网络原因无法访问税局个税系统,此功能暂时无法使用,请确保网络情况正常且允许访问外网"));
head.setDesc("失败");
head.setStatus("N");
baseResponse.setHead(head);
result = JsonUtil.toJsonString(baseResponse);
}
return result;
}
}