HttpsURLConnection openConnection查询

时间:2018-04-28 07:50:43

标签: java sockets networking https httpsurlconnection

我正在使用JAVA Class 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'对象。换句话说,我可以强制HttpsURLConnection调用仅接受主机端口作为参数的其他createSocket()方法。我想从我的代码中创建初始套接字对象。

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 个答案:

答案 0 :(得分:0)

应该可以使用HttpsURLConnection。见这个例子:

http://rtfcode.com/xref/java-1.8/jdk/test/sun/security/ssl/sun/net/www/protocol/https/HttpsURLConnection/HttpsSocketFacTest.java#L168

您可能想要检查createSocket实现中给定套接字是否为空。

您也可以使用Apache HTTP客户端。您可以提供覆盖SSLConnectionSocketFactoryConnectionSocketFactory.connectSocket实施。这会创建初始套接字。

请参阅"自定义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