我尝试使用HTTPS协议连接到网页。 但其回归403回应。 那么如何在不检查证书的情况下连接到HTTPS服务器。 我从StackOverflow中提到了类似的代码。它适用于其他页面,但不适用于wireshark。
package Others;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
public class wireshark {
public static void main(String[] args) throws IOException {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true; // Just allow them all.
}
};
try {
URL url=new URL("https://ask.wireshark.org/questions/634/acc-to-wireshark-999-of-my-outgoing-packets-have-a-bad-checksum");
System.setProperty("jsse.enableSNIExtension", "true");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
// HttpsURLConnection httpConnection=null ;
HttpsURLConnection httpConnection= (HttpsURLConnection) url.openConnection();
httpConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
System.out.println(httpConnection.getResponseCode());
}
catch (GeneralSecurityException e) {
throw new ExceptionInInitializerError(e);
}
}
}
答案 0 :(得分:2)
http 403错误通常与您通过HTTPS连接的方式无关(除非该站点需要客户端证书,而不是您的情况)。 403是禁止的错误代码,可能会被抛出以防止机器人和其他网络爬虫阅读他们的网站。通常,他们使用简单的方法,例如读取用户代理字段来停止机器人。默认情况下,Java程序都使用此用户代理:Java / version,例如Java / 1.8.0_66
在浏览器中以调试模式打开该页面,查看它发送的所有HTTP标头,然后尝试从您的程序发送相同的标题。