0
String currentUrl = "https://www.test.com/";
conn = (HttpsURLConnection) (currentUrl.openConnection())
如果我使用域,一切正常工作。HttpsURLConnection与IP问题
不过,如果我使用域的IP地址,发生
String currentUrl = "https://123.123.123.123:443/";
conn = (HttpsURLConnection) (currentUrl.openConnection());
问题,我得到了SSLPeerUnverifiedException(Hostname 123.123.123.123 not verified
异常,并请求失败。
为了解决这个问题,我只是提供的HostnameVerifier
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
String host = "www.test.com";
return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
}
});
除了
,我要解决的SNI情况相同的问题。
,所以我提供一个自定义的SSLSocketFactory
MySSLSocketFactory sslSocketFactory = new MySSLSocketFactory(conn);
conn.setSSLSocketFactory(sslSocketFactory);
public class MySSLSocketFactory extends SSLSocketFactory{
private HttpsURLConnection conn;
public HalleySSLSocketFactory(HttpsURLConnection conn) {
this.conn = conn;
}
@Override
public Socket createSocket() throws IOException {
return null;
}
@Override
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return null;
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost,
int localPort) throws IOException, UnknownHostException {
return null;
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return null;
}
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException {
return null;
}
@Override
public String[] getDefaultCipherSuites() {
return new String[0];
}
@Override
public String[] getSupportedCipherSuites() {
return new String[0];
}
@Override
public Socket createSocket(Socket plainSocket, String host, int port,
boolean autoClose) throws IOException {
String peerHost = this.conn.getRequestProperty("Host");
if (peerHost == null)
peerHost = host;
InetAddress address = plainSocket.getInetAddress();
if (autoClose) {
plainSocket.close();
}
SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
.getDefault(0);
SSLSocket ssl = (SSLSocket) sslSocketFactory
.createSocket(address, port);
ssl.setEnabledProtocols(ssl.getSupportedProtocols());
// set up SNI before the handshake
try {
java.lang.reflect.Method setHostnameMethod = ssl.getClass()
.getMethod("setHostname", String.class);
setHostnameMethod.invoke(ssl, peerHost);
} catch (Exception e) {
FileLog.w(TAG, "SNI not useable", e);
}
return ssl;
}
}
不幸的是,它还有另外一个问题, 不能重用连接更多,这意味着每个请求必须TCP握手和SSL握手,它会花费很多时间。
所以这里是我的问题, 是否有解决HttpsUrlConnection的直接IP请求问题?
如果没有,我如何重新使用连接根据我上面提到的。