You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

330 lines
13 KiB

package com.fr.plugin.xx.zyjn.utils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.http.HttpResponse;
import com.fr.third.org.apache.http.HttpStatus;
import com.fr.third.org.apache.http.NameValuePair;
import com.fr.third.org.apache.http.client.HttpClient;
import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity;
import com.fr.third.org.apache.http.client.methods.HttpPost;
import com.fr.third.org.apache.http.config.Registry;
import com.fr.third.org.apache.http.config.RegistryBuilder;
import com.fr.third.org.apache.http.conn.socket.ConnectionSocketFactory;
import com.fr.third.org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import com.fr.third.org.apache.http.conn.socket.PlainConnectionSocketFactory;
import com.fr.third.org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import com.fr.third.org.apache.http.conn.ssl.SSLContexts;
import com.fr.third.org.apache.http.conn.ssl.TrustStrategy;
import com.fr.third.org.apache.http.impl.client.CloseableHttpClient;
import com.fr.third.org.apache.http.impl.client.HttpClientBuilder;
import com.fr.third.org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import com.fr.third.org.apache.http.message.BasicNameValuePair;
import com.fr.third.org.apache.http.util.EntityUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author xx
* @Date 2020/12/05
* @Description
**/
public class HttpUtil {
private static HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. "
+ session.getPeerHost());
return true;
}
};
/**
* 发送get请求
*
* @param url
* @param param
* @param header
* @return
* @throws IOException
*/
public static String sendGet(String url, Map<String, String> param, Map<String, String> header) {
String result = "";
BufferedReader in = null;
String urlNameString = url;
try {
if (param != null) {
urlNameString += "?";
urlNameString += param.entrySet()
.stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
}
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
HttpURLConnection connection;
if (url.startsWith("https")) {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
connection = (HttpURLConnection) realUrl.openConnection();
} else {
connection = (HttpURLConnection) realUrl.openConnection();
}
//设置超时时间
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(15000);
// 设置通用的请求属性
if (header != null) {
Iterator<Map.Entry<String, String>> it = header.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println(entry.getKey() + ":::" + entry.getValue());
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
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();
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if (in != null) {
in.close();
}
}catch (Exception e){
FineLoggerFactory.getLogger().error(e,"get url error ,url is:{},error is {}",urlNameString,e.getMessage());
}
return result;
}
public static String sendPost(String url,Map<String,String> header, JSONObject body) {
PrintWriter out = null;
BufferedReader in = null;
String result = StringUtils.EMPTY;
String res = StringUtils.EMPTY;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
HttpURLConnection conn;
if (url.startsWith("https")) {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
conn = (HttpURLConnection) realUrl.openConnection();
} else {
conn = (HttpURLConnection) realUrl.openConnection();
}
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type","application/json;;charset=UTF-8");
//conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork");
if(header != null){
header.forEach((k, v) -> {
conn.setRequestProperty(k, v);
});
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取请求头
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
StringBuffer buffer = new StringBuffer();
// 发送请求参数
if(body != null){
out.print(body.toString());
}
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
res = result;
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(),e);
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException e){
FineLoggerFactory.getLogger().error(e.getMessage(),e);
}
}
return res;
}
private static CloseableHttpClient getHttpsClient() {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF);
// 指定信任密钥存储对象和连接套接字工厂
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// 信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
return true;
}
};
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
// 设置连接管理器
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
// 构建客户端
return HttpClientBuilder.create().setConnectionManager(connManager).build();
}
public static String doFormPost(String url,Map<String, Object> header, Map<String, Object> map, String chartset) {
//声明返回结果
String result = "";
UrlEncodedFormEntity entity = null;
HttpResponse httpResponse = null;
HttpClient httpClient = null;
try {
// 创建连接
httpClient = getHttpsClient();
// 设置请求头和报文
HttpPost httpPost = new HttpPost(url);
if (header != null) {
header.forEach((k, v) -> {
httpPost.setHeader(k, v.toString());
});
}
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
}
entity = new UrlEncodedFormEntity(list, chartset == null ? "UTF-8" : chartset);
httpPost.setEntity(entity);
//执行发送,获取相应结果
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
} else {
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", httpResponse.getStatusLine().getStatusCode(), EntityUtils.toString(httpResponse.getEntity()));
}
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return result;
}
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL","SunJSSE");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
/**
* encode url by UTF-8
* @param url url before encoding
* @return url after encoding
*/
public static String encodeUrl(String url){
String eurl = url;
try {
eurl = URLEncoder.encode(url,"UTF-8");
} catch (UnsupportedEncodingException e) {
}
return eurl;
}
private static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
}