package com.hnkylin.mc.utils;
import org.apache.log4j.Logger;
import org.codehaus.groovy.grails.io.support.IOUtils;
import org.codehaus.groovy.grails.web.json.JSONObject;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
public class HttpUtils {
public static String BOUNDARY = java.util.UUID.randomUUID().toString();
public static String PREFIX = "--", LINEND = "\r\n";
public static String MULTIPART_FROM_DATA = "multipart/form-data";
public static String CHARSET = "UTF-8";
private static final Logger log = Logger.getLogger(HttpUtils.class);
/**
* 发送HTTPS请求
*/
public static JSONObject remoteRequest(String remoteUrl, String filePath, Map
FileInputStream in = null;
OutputStream out = null;
HttpURLConnection conn = null;
JSONObject resposeMess = null;
InputStream ins = null;
ByteArrayOutputStream outStream = null;
try {
// 直接通过主机认证
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
TrustManager[] trustAllCerts = {new TrustAllTrustManager()};
SSLContext sc = SSLContext.getInstance("SSL");
SSLSessionContext sslsc = sc.getServerSessionContext();
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);
File file = new File(filePath);
long fileLength=file.length();
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// 激活主机认证
HttpsURLConnection.setDefaultHostnameVerifier(hv);
remoteUrl=packUrlData(remoteUrl,map);
log.info("cluster migrate remoteUrl "+remoteUrl);
URL url = new URL(remoteUrl);
conn = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setConnectTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/html");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Range", "bytes 0-0/"+fileLength);
conn.setFixedLengthStreamingMode(fileLength);
/**/
conn.connect();
//写参数
StringBuilder sb = packTextData(map);
out = conn.getOutputStream();
//in = new DataInputStream(new FileInputStream(file));
in = new FileInputStream(file);
/*byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
log.info("cluster migrate write ...");
}
out.flush();*/
IOUtils.copy(in,out);
log.info("cluster migrate flush end ...");
// 返回流
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
log.info("cluster migrate result end response"+conn.getResponseMessage());
log.info("cluster migrate result end code"+conn.getResponseCode());
ins = conn.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
while ((count = ins.read(data, 0, 1024)) != -1) {
outStream.write(data, 0, count);
}
String resultStr= new String(outStream.toByteArray(), "UTF-8");
resposeMess = new JSONObject(resultStr);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
log.info("cluster migrate finally ...");
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (ins != null) {
ins.close();
}
if (outStream != null) {
outStream.close();
}
if (conn != null) {
conn.disconnect();
}
}
return resposeMess;
}
/**
* 组装文本参数
*/
public static StringBuilder packTextData( Map
StringBuilder sb =new StringBuilder();
for (Map.Entry
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
return sb;
}
/**
* 组装文件参数
*/
public static StringBuilder packfileData(File file){
StringBuilder requestParams = new StringBuilder();
requestParams.append(PREFIX).append(BOUNDARY).append(LINEND);
requestParams.append("Content-Disposition: form-data; name=\"")
.append("imgfile").append("\"; filename=\"")
.append(file.getName()).append("\"")
.append(LINEND);
requestParams.append("Content-Type:application/octet-stream")
.append(LINEND);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINEND);
requestParams.append(LINEND);// 参数头设置完以后需要两个换行,然后才是参数内容
return requestParams;
}
/**
* 组装url后面的参数
*/
public static String packUrlData(String url,Map
StringBuilder sb =new StringBuilder();
for (Map.Entry
url+='&'+entry.getKey()+'='+entry.getValue();
}
return url;
}
public static JSONObject httpsPost(String remoteUrl, JSONObject params, Map
OutputStreamWriter out = null;
HttpURLConnection conn = null;
JSONObject response = null;
InputStream ins = null;
ByteArrayOutputStream outStream = null;
try {
// 直接通过主机认证
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
TrustManager[] trustAllCerts = {new TrustAllTrustManager()};
SSLContext sc = SSLContext.getInstance("SSL");
SSLSessionContext sslsc = sc.getServerSessionContext();
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// 激活主机认证
HttpsURLConnection.setDefaultHostnameVerifier(hv);
URL url = new URL(remoteUrl);
conn = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setConnectTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Charsert", "UTF-8");
// 设置文件类型:
conn.setRequestProperty("contentType", "application/json");
if (Objects.nonNull(headers)) {
for (String key : headers.keySet()) {
conn.setRequestProperty(key, headers.get(key));
}
}
conn.setRequestProperty("Content-Length", String.valueOf(params.toString().getBytes().length));
/**/
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 写入请求的字符串
out.write(params.toString());
out.flush();
// 返回流
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
ins = conn.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
while ((count = ins.read(data, 0, 1024)) != -1) {
outStream.write(data, 0, count);
}
String resultStr = new String(outStream.toByteArray(), "UTF-8");
response = new JSONObject(resultStr);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (ins != null) {
ins.close();
}
if (outStream != null) {
outStream.close();
}
if (conn != null) {
conn.disconnect();
}
}
return response;
}
}
package com.kdlc.common.utils; import javax.net.ssl.TrustManager; /** * @program: kdlcsoft * @description: * @author: bruce * @create: 2023-03-05 13:42 **/ /** * HTTPS请求证书信任 */ public class TrustAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @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; } }