【问题标题】:HTTPS and HTTP connection in javajava中的HTTPS和HTTP连接
【发布时间】:2017-11-09 13:25:33
【问题描述】:

我知道 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 传递给这个函数吗?

【问题讨论】:

    标签: java http url httpurlconnection


    【解决方案1】:

    在您的代码中:

    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.
    

    因此您可以将Http url 或Https url 传递给您的方法。

    见以下代码:

        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
    

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2011-04-06
      • 2013-03-12
      • 1970-01-01
      • 2021-05-02
      相关资源
      最近更新 更多