java中的HTTPS和HTTP连接

Mys*_*oid 2 java url http httpurlconnection

我知道 HTTPS 扩展了 http。那么这是否意味着我可以做到这一点?

HttpUrlConnection connect = passmyurl.openconnection(url);
Run Code Online (Sandbox Code Playgroud)

HttpsUrlConnection connect = passmyurl.openconnection(url);



public static HttpsURLConnection passmyurl(URL url) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        return connection;
    }
Run Code Online (Sandbox Code Playgroud)

这是否意味着两者都会起作用?由于HTTps扩展了HTTP,这意味着我也可以将HTTP url传递给这个函数吗?

dab*_*cai 5

在您的代码中:

public static HttpsURLConnection passmyurl(URL url) throws IOException {
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    return connection;
}
Run Code Online (Sandbox Code Playgroud)

您应该将返回类型更改HttpsURLConnectionURLConnection。因为url.openConnection()结果的类型是 的子类型URLConnection,确切的类型取决于 paramterurl的协议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.
Run Code Online (Sandbox Code Playgroud)

因此,您可以将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());`
Run Code Online (Sandbox Code Playgroud)

印刷品是:

class sun.net.www.protocol.http.HttpURLConnection
class sun.net.www.protocol.https.HttpsURLConnectionImpl
class sun.net.www.protocol.ftp.FtpURLConnection
Run Code Online (Sandbox Code Playgroud)