java中,如何根据url创建HttpsURLConnection或HttpURLConnection?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/945003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:24:12  来源:igfitidea点击:

In java, how to create HttpsURLConnection or HttpURLConnection based on the url?

javaurlconnection

提问by Adam Plumb

I'm working on a project where I'm creating a class to run http client requests (my class acts as a client). It takes in a url and a request method (GET, POST, PUT, etc) and I want to be able to parse the URL and open a HttpsURLConnection or HttpURLConnection based on whether it is https or http (assume the given urls will always be correct).

我正在开发一个项目,我正在创建一个类来运行 http 客户端请求(我的类充当客户端)。它接受一个 url 和一个请求方法(GET、POST、PUT 等),我希望能够解析 URL 并根据它是 https 还是 http 打开一个 HttpsURLConnection 或 HttpURLConnection(假设给定的 url 将始终是正确的)。

If I do the following:

如果我执行以下操作:

URLConnection conn = url.openConnection();

Then that will automatically create a URLConnection that can accept both http and https, but if I do this then I can't find any way to set a request method (GET, POST, etc), since only the HttpsURLConnection or HttpURLConnection classes have the setRequestMethod method.

然后这将自动创建一个可以接受 http 和 https 的 URLConnection,但是如果我这样做,那么我找不到任何方法来设置请求方法(GET、POST 等),因为只有 HttpsURLConnection 或 HttpURLConnection 类具有setRequestMethod 方法。

If I do something like the following:

如果我执行以下操作:

if(is_https)
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
else
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

Then the connections are created, but I can't access them outside of the if blocks.

然后创建连接,但我无法在 if 块之外访问它们。

Is it possible to do this, or should I just give up and use the apache httpclient classes?

是否可以这样做,或者我应该放弃并使用 apache httpclient 类?

采纳答案by Rob Di Marco

HttpsURLConnectionextends HttpUrlConnection, so you do not need the HttpsUrlConnection, you can just do

HttpsURLConnection扩展了HttpUrlConnection,所以你不需要 HttpsUrlConnection,你可以这样做

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

回答by dfa

since HttpsURLConnection extends HttpURLConnectionyou can declare connas HttpsURLConnection. In this way you can access the common interface (setRequestMethod()).

因为HttpsURLConnection extends HttpURLConnection您可以声明connHttpsURLConnection. 通过这种方式,您可以访问公共接口 ( setRequestMethod())。

In order to access the extension methods (like getCipherSuite(), defined only in the child class HttpsURLConnection) you must use a cast after an instanceof:

为了访问扩展方法(例如getCipherSuite(),仅在子类中定义HttpsURLConnection),您必须在instanceof之后使用强制转换

if (conn instanceof HttpsURLConnection) {
    HttpsURLConnection secured = (HttpsURLConnection) conn;
    String cipher = secured.getCipherSuite();
}