gpt4 book ai didi

ssl - 在 JAVA 中发出 HTTPS 请求并打开 SSL 套接字

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:57 24 4
gpt4 key购买 nike

我正在尝试构建一个登录页面。为此,我想打开一个 SSL 套接字并发出一个 HTTPS 请求,但我在行中收到未知主机异常

SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443);

有人可以告诉我我做错了什么吗?另外,我关闭了主机验证,因为我的程序不需要它。

`public void clickLogin() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {


URL url = new URL ("https://31.21.18.222/room_info/x.txt");
HttpsURLConnection connection = null;
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null); //Make an empty store
InputStream fis = new FileInputStream("C:/Documents and Settings/user/Desktop/PK/localhost.crt");
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
java.security.cert.Certificate cert = cf.generateCertificate(bis);
keyStore.setCertificateEntry("localhost", cert);
}

// write code for turning off client verification
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, tmf.getTrustManagers() , null);
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
SSLSocketFactory sslsf = context.getSocketFactory();
SSLSocket skt = (SSLSocket)sslsf.createSocket("https://31.21.18.222/room_info/x.txt" , 443);
skt.setUseClientMode(true);
SSLSession s = skt.getSession(); // handshake implicitly done
skt.setKeepAlive(true);


connection = (HttpsURLConnection) url.openConnection();

// Host name verification off
connection.setHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
return true;
}
}); `

最佳答案

如果你想用createSocket打开一个套接字,你需要使用主机名(或IP地址),而不是完整的URL:

example : sslsf.createSocket("31.21.18.222" , 443);

另外:

  • 不要使用 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider())(它默认存在)。
  • 最好使用 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) 而不是 X.509,尤其是因为 TMF 的默认算法是PKIX,不是 X.509
  • createSocket 将根据信任 anchor 验证证书,但不会检查主机名(这也是防止 MITM 攻击所必需的)。为此,通常最好使用主机名而不是 IP 地址。

关于ssl - 在 JAVA 中发出 HTTPS 请求并打开 SSL 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17316265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com