JSD-8415 开源任务材料
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.
 
 

310 lines
12 KiB

package com.fr.plugin.schedule.oa;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.third.org.apache.http.HttpResponse;
import com.fr.third.org.apache.http.HttpStatus;
import com.fr.third.org.apache.http.client.HttpClient;
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.PlainConnectionSocketFactory;
import com.fr.third.org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import com.fr.third.org.apache.http.entity.StringEntity;
import com.fr.third.org.apache.http.impl.client.HttpClients;
import com.fr.third.org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
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.cert.CertificateException;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author fr.open
* @Date 2021/08/17
*/
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, 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(),"UTF-8"));
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 doPost(String url, Map<String, Object> header, JSONObject json) {
HttpClient client = HttpClients.createDefault();
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();
}
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, String.valueOf(v));
});
}
try {
StringEntity s = new StringEntity(json.toString(),"UTF-8");
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;
}
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(),e);
}
return null;
}
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("SSLv3");
// 实现一个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;
}
}