java - java中的HTTPS和HTTP连接

标签 java http url httpurlconnection

我知道 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;
    }

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

最佳答案

在您的代码中:

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

您应该将返回类型 HttpsURLConnection 更改为 URLConnection。因为 url.openConnection() 结果的类型是 URLConnection 的子类型,具体类型取决于参数url的协议(protocol)。URL类中openConnection()的实现文档:

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

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

相关文章:

c# - 如何从 http 请求/响应流中获取 PDF

php - 正则表达式查找所有 URL 和标题

http - Ionic 2 - 从存储值中获取 token 并在 HTTP 请求之前设置 header

java - 如何在 Spring Boot 上返回 JSONObject?

java - 可以数组。 sort 对已添加到数组中的枚举进行排序。?

java - 是否可以使用 InheritanceType.SINGLE_TABLE 保存顶级实体?

ruby-on-rails - 防止 ruby​​ on rails 3 解析 JSON post

java - 如何为 Java 配置代理设置?

r - 使用 R 进行快速 url 查询

java - Vector<Customer> C++、List<Customer> 和 Vector<Customer> Java