提问人:SOJSON用户
提问日期:2019-09-03 14:11
热度:21
Java Http请求HTTPS的时候,偶尔会出现这个错误。
Specified key was too long; max key length is 767 bytes ...
怎么办
1条回答
我来回答
soゝso|
2019-09-03 14:17
这个时候是提示需要证书模式访问,如果是重要的接口,还是希望采用安装证书的方式。当然也有一种快捷的方式。就是忽略证书。
下面分享SOJSON.COM使用的一个类。
package com.sojson.www.zhanzhang.utils;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SslUtils {
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager,X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
return;
}
}
/**
* 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
* @throws Exception
*/
public static void ignoreSsl() throws Exception{
HostnameVerifier hv = (urlHostName, session) -> true;
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}
在创建HTTP请求之前加入。
if("https".equalsIgnoreCase(realUrl.getProtocol())){
SslUtils.ignoreSsl();
}
// 打开和URL之间的连接
conn = (HttpURLConnection) realUrl.openConnection();