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.
480 lines
20 KiB
480 lines
20 KiB
3 years ago
|
package com.fr.plugin.nfsq.sso;
|
||
|
|
||
|
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.client.methods.HttpPut;
|
||
|
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.entity.StringEntity;
|
||
|
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.*;
|
||
|
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 fr.open
|
||
|
* @date 2019/4/2
|
||
|
*/
|
||
|
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, Object> param, Map<String, Object> header, String charset) {
|
||
|
String result = "";
|
||
|
BufferedReader in = null;
|
||
|
String urlNameString = url;
|
||
|
try {
|
||
|
if (param != null && !param.isEmpty()) {
|
||
|
urlNameString += "?";
|
||
|
urlNameString += param.entrySet()
|
||
|
.stream()
|
||
|
.map(entry -> entry.getKey() + "=" + entry.getValue().toString())
|
||
|
.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, Object>> it = header.entrySet().iterator();
|
||
|
while (it.hasNext()) {
|
||
|
Map.Entry<String, Object> entry = it.next();
|
||
|
System.out.println(entry.getKey() + ":::" + entry.getValue());
|
||
|
connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
|
||
|
}
|
||
|
}
|
||
|
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();
|
||
|
if(connection.getResponseCode() == 200){
|
||
|
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
|
||
|
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset == null ? "utf-8" : charset));
|
||
|
String line;
|
||
|
while ((line = in.readLine()) != null) {
|
||
|
result += line;
|
||
|
}
|
||
|
if (in != null) {
|
||
|
in.close();
|
||
|
}
|
||
|
}else {
|
||
|
in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), charset == null ? "utf-8" : charset));
|
||
|
String line;
|
||
|
while ((line = in.readLine()) != null) {
|
||
|
result += line;
|
||
|
}
|
||
|
if (in != null) {
|
||
|
in.close();
|
||
|
}
|
||
|
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}",connection.getResponseCode(),result);
|
||
|
return StringUtils.EMPTY;
|
||
|
}
|
||
|
|
||
|
} 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, Object> header, JSONObject body) {
|
||
|
PrintWriter out = null;
|
||
|
BufferedReader in = null;
|
||
|
String result = null;
|
||
|
String res = null;
|
||
|
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");
|
||
|
if (header != null) {
|
||
|
header.forEach((k, v) -> {
|
||
|
conn.setRequestProperty(k, String.valueOf(v));
|
||
|
});
|
||
|
}
|
||
|
// 发送POST请求必须设置如下两行
|
||
|
conn.setDoOutput(true);
|
||
|
conn.setDoInput(true);
|
||
|
//获取请求头
|
||
|
|
||
|
// 获取URLConnection对象对应的输出流
|
||
|
out = new PrintWriter(conn.getOutputStream());
|
||
|
// 发送请求参数
|
||
|
if (body != null) {
|
||
|
FineLoggerFactory.getLogger().error("content data: {}", body.toString());
|
||
|
FineLoggerFactory.getLogger().error("content cover data: {}", new String(body.toString().getBytes("UTF-8"), "UTF-8"));
|
||
|
out.print(new String(body.toString().getBytes("UTF-8"), "UTF-8"));
|
||
|
}
|
||
|
// flush输出流的缓冲
|
||
|
out.flush();
|
||
|
// 定义BufferedReader输入流来读取URL的响应
|
||
|
in = new BufferedReader(
|
||
|
new InputStreamReader(conn.getInputStream()));
|
||
|
String line;
|
||
|
while ((line = in.readLine()) != null) {
|
||
|
result += line;
|
||
|
}
|
||
|
res = result;
|
||
|
if (res.startsWith("null")) {
|
||
|
res = res.replace("null", "");
|
||
|
}
|
||
|
} 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;
|
||
|
}
|
||
|
|
||
|
|
||
|
public static String doJSONPost(String url, Map<String, Object> header, JSONObject json, Map<String, Object> param, String chartset) {
|
||
|
HttpClient client = getHttpsClient();
|
||
|
/*if (url.startsWith("https")) {
|
||
|
SSLContext sslcontext = createIgnoreVerifySSL();
|
||
|
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||
|
.register("http", PlainConnectionSocketFactory.INSTANCE)
|
||
|
.register("https", new SSLConnectionSocketFactory(sslcontext))
|
||
|
.build();
|
||
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||
|
HttpClients.custom().setConnectionManager(connManager);
|
||
|
client = HttpClients.custom().setConnectionManager(connManager).build();
|
||
|
}*/
|
||
|
if (param != null && !param.isEmpty()) {
|
||
|
url += "?";
|
||
|
url += param.entrySet()
|
||
|
.stream()
|
||
|
.map(entry -> entry.getKey() + "=" + entry.getValue())
|
||
|
.collect(Collectors.joining("&"));
|
||
|
}
|
||
|
HttpPost post = new HttpPost(url);
|
||
|
post.setHeader("accept", "*/*");
|
||
|
post.setHeader("connection", "Keep-Alive");
|
||
|
post.setHeader("Content-Type", "application/json");
|
||
|
if (header != null) {
|
||
|
header.forEach((k, v) -> {
|
||
|
post.setHeader(k, v.toString());
|
||
|
});
|
||
|
}
|
||
|
try {
|
||
|
StringEntity s = new StringEntity(json.toString(), chartset == null ? "UTF-8" : chartset);
|
||
|
s.setContentEncoding("UTF-8");
|
||
|
s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
|
||
|
post.setEntity(s);
|
||
|
HttpResponse res = client.execute(post);
|
||
|
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
||
|
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
|
||
|
return result;
|
||
|
} else {
|
||
|
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
|
||
|
}
|
||
|
} catch (Exception e) {
|
||
|
FineLoggerFactory.getLogger().error(e.getMessage(), e);
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
public static String doJSONPut(String url, Map<String, Object> header, JSONObject json, Map<String, Object> param, String chartset) {
|
||
|
HttpClient client = getHttpsClient();
|
||
|
/*if (url.startsWith("https")) {
|
||
|
SSLContext sslcontext = createIgnoreVerifySSL();
|
||
|
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||
|
.register("http", PlainConnectionSocketFactory.INSTANCE)
|
||
|
.register("https", new SSLConnectionSocketFactory(sslcontext))
|
||
|
.build();
|
||
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||
|
HttpClients.custom().setConnectionManager(connManager);
|
||
|
client = HttpClients.custom().setConnectionManager(connManager).build();
|
||
|
}*/
|
||
|
if (param != null && !param.isEmpty()) {
|
||
|
url += "?";
|
||
|
url += param.entrySet()
|
||
|
.stream()
|
||
|
.map(entry -> entry.getKey() + "=" + entry.getValue())
|
||
|
.collect(Collectors.joining("&"));
|
||
|
}
|
||
|
HttpPut post = new HttpPut(url);
|
||
|
post.setHeader("accept", "*/*");
|
||
|
post.setHeader("connection", "Keep-Alive");
|
||
|
post.setHeader("Content-Type", "application/json");
|
||
|
if (header != null) {
|
||
|
header.forEach((k, v) -> {
|
||
|
post.setHeader(k, v.toString());
|
||
|
});
|
||
|
}
|
||
|
try {
|
||
|
StringEntity s = new StringEntity(json.toString(), chartset == null ? "UTF-8" : chartset);
|
||
|
s.setContentEncoding("UTF-8");
|
||
|
s.setContentType("application/json; charset=UTF-8");//发送json数据需要设置contentType
|
||
|
post.setEntity(s);
|
||
|
HttpResponse res = client.execute(post);
|
||
|
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
||
|
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
|
||
|
return result;
|
||
|
} else {
|
||
|
FineLoggerFactory.getLogger().error("Http post form code is {},message is {}", res.getStatusLine().getStatusCode(), EntityUtils.toString(res.getEntity()));
|
||
|
}
|
||
|
} catch (Exception e) {
|
||
|
FineLoggerFactory.getLogger().error(e.getMessage(), e);
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
|
||
|
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();
|
||
|
;
|
||
|
/*if (url.startsWith("https")) {
|
||
|
SSLContext sslcontext = createIgnoreVerifySSL();
|
||
|
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||
|
.register("http", PlainConnectionSocketFactory.INSTANCE)
|
||
|
.register("https", new SSLConnectionSocketFactory(sslcontext))
|
||
|
.build();
|
||
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||
|
HttpClients.custom().setConnectionManager(connManager);
|
||
|
httpClient = HttpClients.custom().setConnectionManager(connManager).build();
|
||
|
}*/
|
||
|
// 设置请求头和报文
|
||
|
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 {
|
||
|
TrustManager[] trustAllCerts = new TrustManager[1];
|
||
|
TrustManager tm = new miTM();
|
||
|
trustAllCerts[0] = tm;
|
||
|
SSLContext sc = 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 TrustManager,
|
||
|
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 CertificateException {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public void checkClientTrusted(
|
||
|
java.security.cert.X509Certificate[] certs, String authType)
|
||
|
throws CertificateException {
|
||
|
return;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static SSLContext createIgnoreVerifySSL() {
|
||
|
try {
|
||
|
SSLContext sc = SSLContext.getInstance("TLSv1.2");
|
||
|
|
||
|
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
|
||
|
X509TrustManager trustManager = new X509TrustManager() {
|
||
|
@Override
|
||
|
public void checkClientTrusted(
|
||
|
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
|
||
|
String paramString) throws CertificateException {
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public void checkServerTrusted(
|
||
|
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
|
||
|
String paramString) throws CertificateException {
|
||
|
}
|
||
|
|
||
|
@Override
|
||
|
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||
|
return null;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
sc.init(null, new TrustManager[]{trustManager}, null);
|
||
|
return sc;
|
||
|
} catch (Exception e) {
|
||
|
FineLoggerFactory.getLogger().error(e.getMessage(), e);
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
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();
|
||
|
|
||
|
}
|
||
|
}
|