在Java中,如何基于url创建HttpsURLConnection或HttpURLConnection? [英] In java, how to create HttpsURLConnection or HttpURLConnection based on the url?

查看:73
本文介绍了在Java中,如何基于url创建HttpsURLConnection或HttpURLConnection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

如果我执行以下操作:

URLConnection conn = url.openConnection();

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

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.

如果我执行以下操作:

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

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

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

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

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

推荐答案

HttpsURLConnection 扩展了 HttpUrlConnection,因此您不需要HttpsUrlConnection,只需执行

HttpsURLConnection extends HttpUrlConnection, so you do not need the HttpsUrlConnection, you can just do

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

这篇关于在Java中,如何基于url创建HttpsURLConnection或HttpURLConnection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆