package com.infinitePossibilities.utils.requestUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.methods.HttpPut;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.SecureRandom;
import java.util.*;
public class HttpUtils {
private static final int REQUEST_TIMEOUT = 10 * 1000; // 设置请求超时10秒钟
private static final int CONNECT_TIMEOUT = 5 * 1000; // 连接超时时间
private static final int SO_TIMEOUT = 10 * 1000; // 数据传输超时
private static final String ENCODING = "UTF-8";
private static CloseableHttpClient httpclient = HttpClients.createDefault();
private static CloseableHttpClient httpsclient;
public HttpUtils() {
}
public static String getHttp(String apiUrl, Map<String, String> paramPairs) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpget = new HttpGet(apiUrl);
List<NameValuePair> params = convert(paramPairs);
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params));
httpget.setURI(new URI(apiUrl + (apiUrl.indexOf("?") == -1 ? "?" : "&") + paramsStr));
httpResponse = httpclient.execute(httpget);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var11) {
throw new Exception(var11);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static byte[] getImgBytes(String apiUrl) {
byte[] body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpget = new HttpGet(apiUrl);
httpResponse = httpsclient.execute(httpget);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toByteArray(entity);
}catch (Exception e) {
System.out.println("httpUtils---err");
}
return body;
}
/**
* Map<String,Object> {"fileName":string,"data":byte[]}
* @param apiUrl
* @return
* @throws Exception
*/
public static Map<String, Object> getPicByte(String apiUrl) throws Exception {
byte[] body = null;
Map<String, Object> map = new HashMap<String, Object>();
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpget = new HttpGet(apiUrl);
httpResponse = httpsclient.execute(httpget);
HttpEntity entity = httpResponse.getEntity();
Header headerContentDis = httpResponse.getFirstHeader("Content-Disposition");
Header headerContentType = httpResponse.getFirstHeader("Content-Type");
if(headerContentDis == null && headerContentType == null) {
return null;
}
String fileName = "";
if(headerContentDis != null) {
String value = headerContentDis.getValue();
System.out.println("获取到的文件名头信息= "+value);
if(StringUtils.isEmpty(value)) {
return null;
}
int indexOf = value.indexOf("\"");
int lastIndexOf = value.lastIndexOf("\"");
if(indexOf >0 && lastIndexOf > 0 && lastIndexOf> indexOf) {
fileName = value.substring(indexOf+1, lastIndexOf);
}
map.put("fileName", fileName);
}
if(headerContentType != null && StringUtils.isEmpty(fileName)) {
String value = headerContentType.getValue();
System.out.println("获取到的文件名头信息= "+value);
if(StringUtils.isEmpty(value)) {
return null;
}
int indexOf = value.indexOf("/");
int lastIndexOf = value.lastIndexOf(";");
fileName = "tk.";
if(indexOf >0 && lastIndexOf > 0 && lastIndexOf> indexOf) {
fileName = fileName + value.substring(indexOf+1, lastIndexOf);
}
map.put("fileName", fileName);
}
body = EntityUtils.toByteArray(entity);
System.out.println(body);
map.put("data", body);
EntityUtils.consume(entity);
} catch (Exception var8) {
throw new Exception(var8);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return map;
}
public static String getHttp(String apiUrl) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpget = new HttpGet(apiUrl);
httpResponse = httpclient.execute(httpget);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var8) {
throw new Exception(var8);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String getHttps(String apiUrl) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpget = new HttpGet(apiUrl);
httpResponse = httpsclient.execute(httpget);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var8) {
throw new Exception(var8);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String postHttp(String apiUrl, Map<String, String> paramPairs) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(apiUrl);
List<NameValuePair> params = convert(paramPairs);
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(uefEntity);
httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var11) {
throw new Exception(var11);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
@SuppressWarnings("unused")
private static String getHttps(String apiUrl, Map<String, String> paramPairs) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpGet httpget = new HttpGet(apiUrl);
List<NameValuePair> params = convert(paramPairs);
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(params));
httpget.setURI(new URI(apiUrl + (apiUrl.indexOf("?") == -1 ? "?" : "&") + paramsStr));
httpResponse = httpsclient.execute(httpget);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var11) {
throw new Exception(var11);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String postHttps(String apiUrl, Map<String, String> paramPairs){
String body = null;
CloseableHttpResponse httpResponse = null;
try {
System.out.println("--------1: {}"+apiUrl);
HttpPost httpPost = new HttpPost(apiUrl);
List<NameValuePair> params = convert(paramPairs);
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(uefEntity);
System.out.println("--------5");
System.setProperty("https.protocols", "TLSv1,SSLv3");
httpResponse = httpsclient.execute(httpPost);
System.out.println("--------6");
HttpEntity entity = httpResponse.getEntity();
System.out.println("--------7");
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
}
}
}
return body;
}
public static String postJsonHttps(String apiUrl, Map<String, Object> paramPairs) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(apiUrl);
String jsonString = JSONObject.toJSONString(paramPairs);
StringEntity paramEntity = new StringEntity(jsonString, "UTF-8");
httpPost.addHeader("content-type", "application/json");
httpPost.setEntity(paramEntity);
httpResponse = httpsclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var11) {
throw new Exception(var11);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String postJsonHttps(String apiUrl, String requestBody) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(apiUrl);
StringEntity paramEntity = new StringEntity(requestBody, "UTF-8");
httpPost.addHeader("content-type", "application/json");
httpPost.setEntity(paramEntity);
httpResponse = httpsclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var10) {
throw new Exception(var10);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String postJson(String apiUrl, String requestBody, Map<String, String> headers) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(apiUrl);
StringEntity paramEntity = new StringEntity(requestBody, "UTF-8");
httpPost.addHeader("content-type", "application/json");
if (headers != null) {
Iterator<String> var7 = headers.keySet().iterator();
while (var7.hasNext()) {
String key = (String) var7.next();
httpPost.addHeader(key, (String) headers.get(key));
}
}
httpPost.setEntity(paramEntity);
httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var12) {
throw new Exception(var12);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String postJsonHttps(String apiUrl, String requestBody, Map<String, String> headers)
throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(apiUrl);
StringEntity paramEntity = new StringEntity(requestBody, "UTF-8");
httpPost.addHeader("content-type", "application/json");
if (headers != null) {
Iterator<String> var7 = headers.keySet().iterator();
while (var7.hasNext()) {
String key = (String) var7.next();
httpPost.addHeader(key, (String) headers.get(key));
}
}
httpPost.setEntity(paramEntity);
httpResponse = httpsclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var12) {
throw new Exception(var12);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String putXmlHttps(String apiUrl, String requestBody) throws Exception {
return putXmlHttps(apiUrl, requestBody, null);
}
public static String putXmlHttps(String apiUrl, String requestBody, Map<String, String> headers) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPut httpPost = new HttpPut(apiUrl);
StringEntity paramEntity = new StringEntity(requestBody, "UTF-8");
httpPost.addHeader("content-type", "application/xml");
if (headers != null) {
Iterator<String> var7 = headers.keySet().iterator();
while (var7.hasNext()) {
String key = (String) var7.next();
httpPost.addHeader(key, (String) headers.get(key));
}
}
httpPost.setEntity(paramEntity);
httpResponse = httpsclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (Exception var12) {
throw new Exception(var12);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
public static String requestService(String toURL, String data) throws Exception {
StringBuffer bs = new StringBuffer();
URL url = new URL(toURL);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setRequestMethod("POST");
urlcon.setUseCaches(false);
urlcon.setConnectTimeout(30000);
urlcon.setReadTimeout(30000);
urlcon.setDoInput(true);
urlcon.setDoOutput(true);
urlcon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = urlcon.getOutputStream();
out.write(data.getBytes("UTF-8"));
out.flush();
out.close();
urlcon.connect();
InputStream is = urlcon.getInputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
String l = null;
while ((l = buffer.readLine()) != null) {
bs.append(l);
}
return bs.toString();
}
public static String postXmlHttps(String apiUrl, String requestBody) throws Exception {
return postXmlHttps(apiUrl, requestBody, null);
}
public static String postXmlHttps(String apiUrl, String requestBody, Map<String, String> headers) throws Exception {
String body = null;
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(apiUrl);
StringEntity paramEntity = new StringEntity(requestBody, "UTF-8");
httpPost.addHeader("content-type", "application/xml");
if (headers != null) {
Iterator<String> var7 = headers.keySet().iterator();
while (var7.hasNext()) {
String key = (String) var7.next();
httpPost.addHeader(key, (String) headers.get(key));
}
}
httpPost.setEntity(paramEntity);
httpResponse = httpsclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
body = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
} catch (Exception var12) {
throw new Exception(var12);
} finally {
if (httpResponse != null) {
httpResponse.close();
}
}
return body;
}
static {
SSLContext sslctxt;
try {
sslctxt = SSLContext.getInstance("TLS");
sslctxt.init((KeyManager[]) null, new TrustManager[] { new MyX509TrustManager() }, new SecureRandom());
} catch (Exception var2) {
throw new RuntimeException("https client初始化错误");
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctxt,new String[] { "TLSv1" },
null,
NoopHostnameVerifier.INSTANCE);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setConnectionRequestTimeout(REQUEST_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build();
httpsclient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfig).setMaxConnTotal(50).build();
}
public static List<NameValuePair> convert(Map<String, String> pairs) {
List<NameValuePair> result = new ArrayList<NameValuePair>();
Iterator<String> var2 = pairs.keySet().iterator();
while (var2.hasNext()) {
String key = (String) var2.next();
NameValuePair pair = new BasicNameValuePair(key, (String) pairs.get(key));
result.add(pair);
}
return result;
}
}
package com.infinitePossibilities.utils.requestUtils;
import javax.net.ssl.X509TrustManager;
import java.math.BigInteger;
import java.security.Principal;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
public MyX509TrustManager() {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (null != chain) {
for(int k = 0; k < chain.length; ++k) {
X509Certificate cer = chain[k];
this.print(cer);
}
}
System.out.println("check client trusted. authType=" + authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (null != chain) {
for(int k = 0; k < chain.length; ++k) {
X509Certificate cer = chain[k];
this.print(cer);
}
}
System.out.println("check servlet trusted. authType=" + authType);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
System.out.println("get acceptedissuer");
return null;
}
private void print(X509Certificate cer) {
int version = cer.getVersion();
String sinname = cer.getSigAlgName();
String type = cer.getType();
String algorname = cer.getPublicKey().getAlgorithm();
BigInteger serialnum = cer.getSerialNumber();
Principal principal = cer.getIssuerDN();
String principalname = principal.getName();
System.out.println("version=" + version + ", sinname=" + sinname + ", type=" + type + ", algorname=" + algorname + ", serialnum=" + serialnum + ", principalname=" + principalname);
}
}