package **.tool;
import cn.hutool.http.ssl.TrustAnyHostnameVerifier;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.utils.URIBuilder;
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.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpClientService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);
private static final int SUCCESS_CODE = 200;
public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception {
JSONObject jsonObject = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
SSLConnectionSocketFactory scsf = getSSLConnectionSocketFactory("/172.18.3.30(12345678).pfx", "12345678");
httpClientBuilder = httpClientBuilder.setSSLSocketFactory(scsf);
client = httpClientBuilder.build();
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.addParameters(nameValuePairList);
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
try {
jsonObject = JSONObject.parseObject(result);
return jsonObject;
} catch (Exception e) {
return result;
}
} else {
LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");
}
} catch (Exception e) {
LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);
} finally {
response.close();
client.close();
}
return null;
}
public static Object sendPost(String url, List<NameValuePair> nameValuePairList,String path,String passWord) throws Exception {
JSONObject jsonObject = null;
CloseableHttpClient client = null;
new HttpClientService();
CloseableHttpResponse response = null;
try {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
SSLConnectionSocketFactory scsf = getSSLConnectionSocketFactory(path, passWord);
httpClientBuilder = httpClientBuilder.setSSLSocketFactory(scsf);
client = httpClientBuilder.build();
HttpPost post = new HttpPost(url);
StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
post.setEntity(entity);
post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (SUCCESS_CODE == statusCode) {
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
try {
jsonObject = JSONObject.parseObject(result);
return jsonObject;
} catch (Exception e) {
return result;
}
} else {
LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");
}
} catch (Exception e) {
LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);
} finally {
response.close();
client.close();
}
return null;
}
public static List<NameValuePair> getParams(Object[] params, Object[] values) {
boolean flag = params.length > 0 && values.length > 0 && params.length == values.length;
if (flag) {
List<NameValuePair> nameValuePairList = new ArrayList<>();
for (int i = 0; i < params.length; i++) {
nameValuePairList.add(new BasicNameValuePair(params[i].toString(), values[i].toString()));
}
return nameValuePairList;
} else {
LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197, "请求参数为空且参数长度不一致");
}
return null;
}
private static Map<String, SSLConnectionSocketFactory> crtMap = new HashMap<String, SSLConnectionSocketFactory>();
private static SSLConnectionSocketFactory getSSLConnectionSocketFactory(String caPath, String caPassword) {
SSLConnectionSocketFactory scsf = null;
try {
if (crtMap.containsKey(caPath)) {
return crtMap.get(caPath);
}
KeyStore keyStore = KeyStore.getInstance("PKCS12");
org.springframework.core.io.Resource resource = new ClassPathResource(caPath);
InputStream fontInputStream = resource.getInputStream();
keyStore.load(fontInputStream, caPassword.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
})
.loadKeyMaterial(keyStore, caPassword.toCharArray())
.build();
scsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
if (scsf != null && !crtMap.containsKey(caPath)) {
crtMap.put(caPath, scsf);
}
} catch (Exception ex) {
System.out.println(String.format("%s 初始化证书异常:caPath=%s,caPassword=%s,异常信息:%s",
DateTimeUtil.getDateTimeString2(), caPath, caPassword, ex.getMessage()));
}
return scsf;
}
public static String doPost(String url, String params) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
int timeout = 30 * 1000;
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
conn.connect();
if (params != null) {
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(params);
out.flush();
out.close();
}
InputStreamReader r = new InputStreamReader(conn.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(r);
String line;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("调用远端服务出错", e);
}
}
}
public static String request(String url, String method, String paramType, HashMap<String, String> bodyParams, HashMap<String, String> headerParams) {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
switch (paramType) {
case "json":
mediaType = MediaType.parse("application/json");
break;
case "form":
mediaType = MediaType.parse("application/x-www-form-urlencoded");
break;
default:
break;
}
String s1 = JSONObject.toJSONString(bodyParams);
RequestBody body = RequestBody.create(mediaType, s1);
Request.Builder requestBuilder = new Request.Builder()
.url(url)
.method(method, body);
if (headerParams.size() > 0) {
for (String s : headerParams.keySet()) {
requestBuilder.addHeader(s, headerParams.get(s));
}
}
Request request = requestBuilder.build();
Response response = null;
String string = "";
try {
response = client.newCall(request).execute();
string = response.body().string();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(url + "请求返回异常!" + response.code());
}
if (response.code() != 200) {
throw new RuntimeException(url + "请求返回异常!" + response.code());
}
return string;
}
public static String setRequestbyHttps( JSONObject bodyParams, String url, JSONObject header) {
SSLContext sslcontext = createIgnoreVerifySSL();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
HttpPost post = new HttpPost(url);
List<NameValuePair> list = new ArrayList<>();
Iterator<Map.Entry<String, Object>> iterator = bodyParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
String s = entry.getKey().toString();
String s1 = entry.getValue().toString();
list.add(new BasicNameValuePair(s, s1));
}
HttpEntity entity = new UrlEncodedFormEntity(list, Charsets.UTF_8);
if (header != null && header.size() > 0) {
Set<Map.Entry<String, Object>> entrySet = header.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
post.setHeader(entry.getKey(), entry.getValue().toString());
}
}
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(entity);
try {
CloseableHttpResponse response = client.execute(post);
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
throw new RuntimeException(e.toString());
} finally {
post.releaseConnection();
}
}
public static SSLContext createIgnoreVerifySSL() {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return sslContext;
}
public static String returnJson(String url, String param, String contentType) {
StringBuilder sb = new StringBuilder();
HttpURLConnection httpConnection = null;
try {
URL restServiceURL = new URL(url);
httpConnection = (HttpURLConnection) restServiceURL.openConnection();
if (param == null) {
httpConnection.connect();
} else {
httpConnection.setRequestMethod("POST");
httpConnection.setConnectTimeout(60 * 1000);
httpConnection.setReadTimeout(60 * 1000);
if ("json".equals(contentType)) {
httpConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
} else if ("form".equals(contentType)) {
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
}
httpConnection.setRequestProperty("Accept", "application/json, text/plain, */*");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.connect();
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(param.getBytes("UTF-8"));
outputStream.flush();
}
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "utf-8"));
String output;
while ((output = responseBuffer.readLine()) != null) {
sb.append(output);
}
httpConnection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(String.format("%s Rest服务调用异常:Url=%s,param=%s,异常信息:%s",
DateTimeUtil.getDateTimeString2(), url, param, ex.getMessage()));
throw new RuntimeException(ex.getMessage());
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return sb.toString();
}
private static Map<String, SSLConnectionSocketFactory> crtMap = new HashMap<String, SSLConnectionSocketFactory>();
private static SSLConnectionSocketFactory getSSLConnectionSocketFactory(String caPath, String caPassword) {
SSLConnectionSocketFactory scsf = null;
try {
if (crtMap.containsKey(caPath)) {
return crtMap.get(caPath);
}
KeyStore keyStore = KeyStore.getInstance("PKCS12");
org.springframework.core.io.Resource resource = new ClassPathResource(caPath);
InputStream fontInputStream = resource.getInputStream();
keyStore.load(fontInputStream, caPassword.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
})
.loadKeyMaterial(keyStore, caPassword.toCharArray())
.build();
scsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
if (scsf != null && !crtMap.containsKey(caPath)) {
crtMap.put(caPath, scsf);
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(String.format("%s 初始化证书异常:caPath=%s,caPassword=%s,异常信息:%s",
DateTimeUtil.getDateTimeString2(), caPath, caPassword, ex.getMessage()));
}
return scsf;
}
public static String returnJson(String url, String param, String contentType, boolean isHttps, String caPath, String caPassword) {
StringBuilder sb = new StringBuilder();
CloseableHttpClient httpClient = null;
try {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
if (isHttps) {
SSLConnectionSocketFactory scsf = getSSLConnectionSocketFactory(caPath, caPassword);
httpClientBuilder = httpClientBuilder.setSSLSocketFactory(scsf);
}
httpClient = httpClientBuilder.build();
StringEntity entity = new StringEntity(param, ContentType.APPLICATION_FORM_URLENCODED);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(String.format("%s Rest服务调用异常:Url=%s,param=%s,异常信息:%s",
DateTimeUtil.getDateTimeString2(), url, param, ex.getMessage()));
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static String postJsonRequestByCrt(String url, String param, String contentType, boolean isHttps, String caPath, String caPassword){
StringBuilder sb = new StringBuilder();
CloseableHttpClient httpClient = null;
try {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
if (isHttps) {
SSLConnectionSocketFactory scsf = getSSLConnectionSocketFactory(caPath, caPassword);
httpClientBuilder = httpClientBuilder.setSSLSocketFactory(scsf);
}
httpClient = httpClientBuilder.build();
StringEntity entity = new StringEntity(param, ContentType.APPLICATION_JSON);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(String.format("%s Rest服务调用异常:Url=%s,param=%s,异常信息:%s",
DateTimeUtil.getDateTimeString2(), url, param, ex.getMessage()));
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static String PostForGateWay(String url, String interfaceName, String methodName, Object... param) {
StringBuilder sb = new StringBuilder();
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("interfaceName", interfaceName)
.addFormDataPart("methodName", methodName);
if (param.length > 0) {
for (int i = 0; i < param.length; i++) {
Object arg = param[i];
builder.addFormDataPart("args[]", arg.toString());
}
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.method("POST", body)
.build();
Response response;
try {
response = client.newCall(request).execute();
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(response.body().byteStream(), "utf-8"));
String output;
while ((output = responseBuffer.readLine()) != null) {
sb.append(output);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static String sendGet(String url) {
String result = "";
FileOutputStream fs = null;
FileInputStream fi = null;
InputStream inStream = null;
try {
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
Map<String, List<String>> map = connection.getHeaderFields();
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
inStream = connection.getInputStream();
File file = new File("C:\\Users\\xk\\Desktop\\test.7z");
fi = new FileInputStream(file);
byte[] bytes = new byte[fi.available()];
fi.read(bytes);
result = new BASE64Encoder().encode(bytes).replaceAll("\r", "").replaceAll("\n", "");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
finally {
try {
if (fs != null) {
fs.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
try {
if (inStream != null) {
inStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}