java HttpsURLConnection openConnection查询
我正在使用JAVA类HttpsURLConnection
从HTTPS网站获取内容。我正在使用我自己的SSLSocketFactory
下面的代码片段:
HttpsURLConnection conn = (HttpsURLConnection) new java.net.URL("https", google.com, 443, "/").openConnection();
conn.setHostnameVerifier(new hver());
conn.setReadTimeout(0);
conn.setSSLSocketFactory(my.sslSocketFactory);//mine
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
如果看到第一个createSocket(...)
方法,HttpsURLConnection
本身创建了一个Socket
对象“so”,并将其作为参数传递。有没有办法从我的代码中创建“so”对象。换句话说,我可以强制HttpsURLConnection
调用其他只接受主机端口作为参数的createSocket()
方法。我只想从代码中创建初始socket对象
public class CustomSocketFactoty extends SSLSocketFactory {
// method 1
@Override
public Socket createSocket(*Socket so*, String host, int port,
boolean autoClose) throws IOException {
// HttpsURLConnection itself creating ( in parameter )socket object Socket so and passing it here , Instead I want to create that Socket object so from my code.
// it is called from - conn.connect();
return ...;
}
@Override
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
// This method never called
return ...;
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
// This method never called
return ...;
}
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException {
// This method never called
return ...;
}
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException {
// This method never called
return ...;
}
}
多谢各位
# 1 楼答案
应该可以使用^{} 。请参见此示例:
http://rtfcode.com/xref/java-1.8/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/HttpsSocketFacTest.java#L168
您可能需要检查createSocket实现中给定的套接字是否为null
您还可以使用ApacheHTTP客户端。您可以提供覆盖^{} 的^{} 实现。这将创建初始套接字
请参见“自定义SSL上下文”示例:
http://hc.apache.org/httpcomponents-client-ga/examples.html
http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java