请求第三方Https地址忽略SSL证书校验
说明:个人使用记录
需要依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.12</version>
</dependency>
首先创建忽略工具
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class TrustAllTrustManager implements TrustManager, X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
方式一: HttpURLConnection
需要在请求之前忽略ssl协议,这里是直接使用静态方法初始化时就执行了文章来源:https://www.toymoban.com/news/detail-846459.html
static{
//直接通过主机认证
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
TrustManager[] trustManagers = {new TrustAllTrustManager()};
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
SSLSessionContext sslc = sc.getServerSessionContext();
sslc.setSessionTimeout(0);
sc.init(null,trustManagers,null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//激活主机认证
HttpsURLConnection.setDefaultHostnameVerifier(verifier);
} catch (Exception e) {
e.printStackTrace();
}
}
方式二:HttpGet 或 HttpPost
也需要在请求接口之前忽略SSL文章来源地址https://www.toymoban.com/news/detail-846459.html
//记得try 或 throws 异常
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
SSLContexts.custom.loadTrustMaterial(null,
new TrustSelfSignedStrategy()).build(),NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();
//请求
HttpGet request = new HttpGet("请求地址");
举例:请求第三方接口 并 上传文件
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* dms 交互物文件处理
*/
@Component
public class DmsHelper {
static{
//直接通过主机认证
HostnameVerifier verifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
TrustManager[] trustManagers = {new TrustAllTrustManager()};
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
SSLSessionContext sslc = sc.getServerSessionContext();
sslc.setSessionTimeout(0);
sc.init(null,trustManagers,null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//激活主机认证
HttpsURLConnection.setDefaultHostnameVerifier(verifier);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试使用
*/
public static void main(String[] args) throws Exception {
String filepath = "上传的文件地址";
String urlStr = "第三方接口";
//form-data 参数
Map<String, String> textMap = new HashMap<String, String>();
textMap.put("name", "1");
//上传的文件
Map<String, String> fileMap = new HashMap<String, String>();
fileMap.put("file", filepath);
String ret = formUpload(urlStr, textMap, fileMap);
System.out.println(ret);
}
/**
* 上传图片
* @param urlStr
* @param textMap
* @param fileMap
* @return
*/
public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName();
String contentType = filename.substring(filename.lastIndexOf(".")+1,filename.length());//文件类型
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
* md5加密
*/
public static String GenerateSignature(String str){
String signature = "";
try{
//创建一个提供信息摘要算法的对象,初始化为md5算法对象
MessageDigest md = MessageDigest.getInstance("MD5");
//计算后获得字节数组
byte[] bytes = md.digest(str.getBytes("utf-8"));
//把数组每一字节换成16进制连成md5字符串
signature = bytesToHex(bytes);
}catch (Exception e) {
e.printStackTrace();
}
return signature;
}
public static String bytesToHex(byte[] bytes) {
StringBuffer md5str = new StringBuffer();
//把数组每一字节换成16进制连成md5字符串
int digital;
for (int i = 0; i < bytes.length; i++) {
digital = bytes[i];
if (digital < 0) {
digital += 256;
}
if (digital < 16) {
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
return md5str.toString();
}
}
到了这里,关于请求第三方Https地址忽略SSL证书校验的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!