我知道https扩展了http。那是不是意味着我能做到?

HttpUrlConnection connect = passmyurl.openconnection(url);


HttpsUrlConnection connect = passmyurl.openconnection(url);



public static HttpsURLConnection passmyurl(URL url) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        return connection;
    }

这是否意味着两者都能奏效?因为https扩展了http,这意味着我也可以向这个函数传递一个http url?

最佳答案

在你的代码中:

public static HttpsURLConnection passmyurl(URL url) throws IOException {
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    return connection;
}

您应该将返回类型HttpsURLConnection更改为URLConnection。因为url.openConnection()结果的类型是URLConnection的子类型,而确切的类型取决于参数url的协议。openConnection()类中URL的实现文档:
If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

因此您可以将Httpurl或Httpsurl传递给您的方法。
请参见以下代码:
    URLConnection httpConnection = new URL("http://test").openConnection();
    System.out.println(httpConnection.getClass());
    URLConnection httpsConnection = new URL("https://test").openConnection();
    System.out.println(httpsConnection.getClass());
    URLConnection ftpConnection = new URL("ftp://test").openConnection();
    System.out.println(ftpConnection.getClass());`

印刷品是:
class sun.net.www.protocol.http.HttpURLConnection
class sun.net.www.protocol.https.HttpsURLConnectionImpl
class sun.net.www.protocol.ftp.FtpURLConnection

关于java - Java中的HTTPS和HTTP连接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44425397/

10-10 05:46