使用 HttpsURLConnection 进行 HTTP 和 HTTPS 请求

时间:2020-12-30 16:30:24

标签: java api

有没有办法使用 HttpsURLConnection 来做 HTTP 和 HTTPS 请求?

我只使用一种方法来执行 API 请求,但在 localhost 中我没有使用 https,所以我想使用 HttpsURLConnection 来执行 https 和 http 请求,而无需检查协议来创建 HttpsURLConnection 或 HttpURLConnection

谢谢! 对不起,我的英语

2 个答案:

答案 0 :(得分:0)

我不明白问题所在。

URL 可以是 HTTP 或 HTTPS,无需更改任何代码:

URL cUrl = new URL("http://www.google.com");
//cUrl = new URL("https://www.google.com");   //<-- decomment this line to use an HTTPS
final URLConnection cURLConnection = cUrl.openConnection();
cURLConnection.connect();
if (cURLConnection instanceof HttpURLConnection) ...when url=http://...
else if (cURLConnection instanceof HttpsURLConnection) ...when url=https://...
else ...

HttpsURLConnection 扩展了 HttpURLConnection,因此您可以考虑始终拥有一个“HttpURLConnection”对象,除非/当您需要使用特定的 HttpsURLConnection 方法时,您可以使用“instanceof”检查实例。

答案 1 :(得分:0)

现在我用emandt建议之类的东西解决了

URLConnection conn = url.openConnection();
HttpsURLConnection httpsConn = null;
HttpURLConnection httpConn = null;
boolean isOverHttps = conn instanceof HttpsURLConnection;

if (isOverHttps) {
    httpsConn = (HttpsURLConnection) conn;
    httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
}else{
    httpConn = (HttpURLConnection) conn;
}

并设置参数并获得响应

(isOverHttps ? httpsConn : httpConn).setRequestProperty("Content-Type", service.getConTypeService());

BufferedReader br = new BufferedReader(new InputStreamReader((isOverHttps ? httpsConn : httpConn).getInputStream(), "utf-8"));

相关问题