package awb.aweb_soa.global.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import awb.aweb_soa.global.exception.SOAException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @author 马弦
* @date 2017年10月23日 下午2:49 HttpClient工具类
*
* 2018年7月25日14:20:27
* 重构 加强
*
*/
public class HttpUtil {
private static final Logger LOGGER = LoggerFactory
.getLogger(HttpUtil.class);
private static HttpClient httpClient;
private static final String CONFIG_FILE_PATH="/httpclient.properties";
private static final String SSL_VERSION_KEY="https.ssl.version";//
private static final String TLS_VERSION_KEY="https.tls.version";//TLSv1,TLSv1.1,TLSv1.2
private static final String CIPHER_SUITES_KEY="https.ciphersuites";//null
private static final String KEEP_ALIVE_TIME_KEY="http.defaultkeepalivetime";//20000
static {
try {
Map<String,String> config=MapBuilder.<String,String>hashMap()
.map(SSL_VERSION_KEY, "SSLv3")
.map(TLS_VERSION_KEY, "TLSv1,TLSv1.1,TLSv1.2")
.map(CIPHER_SUITES_KEY, null)
.map(KEEP_ALIVE_TIME_KEY, "20000")
.build();
try(InputStream in=HttpUtil.class.getResourceAsStream(CONFIG_FILE_PATH)){
Properties properties=new Properties();
properties.load(in);
properties.forEach((key,value)->config.put((String)key, (String)value));
}catch(Exception e){
LOGGER.warn("加载HttpClient配置失败",e);
}
ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator
(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase
("timeout")) {
return Long.parseLong(value) * 1000;
}
}
return Integer.parseInt(config.get(KEEP_ALIVE_TIME_KEY));//如果没有约定,则默认定义时长为20s
}
};
SSLContext sslContext = SSLContext.getInstance(config.get(SSL_VERSION_KEY));
sslContext.init(null, new TrustManager[]{
new X509TrustManager(){
@Override
public void checkClientTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {}
@Override
public void checkServerTrusted(
X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {return null;}
}
}, null);
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
sslContext,
config.get(TLS_VERSION_KEY).trim().split("[\\ \\r\\n]*,[\\ \\r\\n]*"),
config.get(CIPHER_SUITES_KEY)==null?null:config.get(CIPHER_SUITES_KEY).trim().split("[\\ \\r\\n]*,[\\ \\r\\n]*"), //
(paramString,paramSSLSession)->true
);
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",sslSocketFactory)
.build());
connectionManager.setMaxTotal(500);
connectionManager.setDefaultMaxPerRoute(50);//例如默认每路由最高50并发,具体依据业务来定
connectionManager.setValidateAfterInactivity(60000);
httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setKeepAliveStrategy(myStrategy)
.build();
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(),e);
}
}
/**
* get请求
*
* @return
*/
public static String doGet(String url) {
try {
HttpClient client = httpClient;
// 发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/** 请求发送成功,并得到响应 **/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
/** 读取服务器返回过来的json字符串数据 **/
String strResult = EntityUtils.toString(response.getEntity());
return strResult;
}
} catch (IOException e) {
throw new IllegalStateException("GET 接口调用失败 URL:"+url+" "+e.getMessage(),e);
}
return null;
}
/**
* post请求(用于key-value格式的参数)
*
* @param url
* @param params
* @return
* @throws IOException
* @throws URISyntaxException
*/
public static String doPost(String url, Map params) throws IOException,
URISyntaxException {
String errorMsg;
BufferedReader in = null;
// 定义HttpClient
HttpClient client = httpClient;
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));
// 设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if (code == 200) { // 请求成功
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(), "utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
JSONObject resMap = JSON.parseObject(sb.toString());
if (resMap == null) {
return "";
}
if (resMap.get("errorMsg") == null) {
return sb.toString();
} else {
errorMsg = JSON.parseObject(sb.toString()).get("errorMsg")
.toString();
if (errorMsg != null && !errorMsg.equals(""))
throw SOAException.error("SA6102", errorMsg);
return sb.toString();
}
} else { //
throw SOAException.error("SA6102", "状态码:" + code);
}
}
/**
* post请求(用于key-value格式的参数)
*
* @param url
* @param params
* @return
* @throws IOException
* @throws URISyntaxException
*/
public static String doPost2(String url, Map<String, String> params) {
List<NameValuePair> nvps = params
.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry
.getValue())).collect(Collectors.toList());
// 实例化HTTP方法
HttpPost request;
try {
request = new HttpPost(new URI(url));
} catch (URISyntaxException e1) {
throw new RuntimeException("http配置错误", e1);
}
// 设置参数
request.setEntity(new UrlEncodedFormEntity(nvps, Charset
.forName("UTF-8")));
// 定义HttpClient
try {
HttpResponse response = httpClient.execute(request);
int code = response.getStatusLine().getStatusCode();
String responseString = EntityUtils.toString(response.getEntity(),
Charset.forName("UTF-8"));
if (HttpStatus.SC_OK == code) { // 请求成功
return responseString;
} else { //
LOGGER.error("HTTP:" + code);
LOGGER.error(responseString);
throw new IllegalStateException("Http接口调用失败,URL:" + url
+ ", 状态码:" + code);
}
} catch (Exception e) {
throw new IllegalStateException("Http接口调用失败," + e.getMessage(), e);
}
}
/**
* post请求(用于请求json格式的参数)
*
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
} catch(Exception e){
throw new IllegalStateException("接口调用失败,URL:"+url+" " +e.getMessage(),e);
}
return null;
}
/**
* post请求文件(用于key-value格式的参数)
*
* @param url
* @param params
* @param name 文件参数名称
* @param file 文件路径
*
* @return
* @throws IOException
* @throws URISyntaxException
*/
public static String doPostFile(String url, Map<String, String> params,String name,Path file) {
Assert.isTrue(Files.exists(file)&&Files.isRegularFile(file), "file 参数不正确 "+file);
// 实例化HTTP方法
HttpPost request;
try {
request = new HttpPost(new URI(url));
} catch (URISyntaxException e1) {
throw new RuntimeException("http配置错误", e1);
}
try(InputStream stream=Files.newInputStream(file)){
MultipartEntityBuilder entityBuilder=MultipartEntityBuilder.create()
.addBinaryBody(name, stream,ContentType.DEFAULT_BINARY,file.getFileName().toString());
entityBuilder.setCharset(Charset.forName("UTF-8"));
ContentType contentType=ContentType.create("text/plain", Charset
.forName("UTF-8"));
params.forEach((key,value)->{
entityBuilder.addTextBody(key, value, contentType);
});
// 设置参数
request.setEntity(entityBuilder.build());
// 定义HttpClient
HttpResponse response = httpClient.execute(request);
int code = response.getStatusLine().getStatusCode();
String responseString = EntityUtils.toString(response.getEntity(),
Charset.forName("UTF-8"));
if (HttpStatus.SC_OK == code) { // 请求成功
return responseString;
} else { //
LOGGER.error("HTTP:" + code);
LOGGER.error(responseString);
throw new IllegalStateException("Http接口调用失败,URL:" + url
+ ", 状态码:" + code);
}
} catch (Exception e) {
throw new IllegalStateException("Http接口调用失败," + e.getMessage(), e);
}
}
public static void doDownloadFile(String url, Map<String, String> params,OutputStream out){
List<NameValuePair> nvps = params
.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry
.getValue())).collect(Collectors.toList());
// 实例化HTTP方法
HttpPost request;
try {
request = new HttpPost(new URI(url));
} catch (URISyntaxException e1) {
throw new RuntimeException("http配置错误", e1);
}
// 设置参数
request.setEntity(new UrlEncodedFormEntity(nvps, Charset
.forName("UTF-8")));
// 定义HttpClient
try {
HttpResponse response = httpClient.execute(request);
int code = response.getStatusLine().getStatusCode();
if (HttpStatus.SC_OK == code) { // 请求成功
response.getEntity().writeTo(out);
} else { //
LOGGER.error("HTTP:" + code);
String responseString = EntityUtils.toString(response.getEntity(),
Charset.forName("UTF-8"));
LOGGER.error(responseString);
throw new IllegalStateException("Http接口调用失败,URL:" + url
+ ", 状态码:" + code);
}
} catch (Exception e) {
throw new IllegalStateException("Http接口调用失败," + e.getMessage(), e);
}
}
public static void main(String[] args) {
System.out.println(doPost2("https://localhost:8443/",Collections.emptyMap()));
// System.out.println(Arrays.asList(" 123 , 2333, \n 333\n, 444 ".trim().split("[\\ \\r\\n]*,[\\ \\r\\n]*")));
}
}