在同一个变量中支持HttpURLConnection和HttpsURLConnection是可能的,但需要根据实际的请求类型来选择使用哪种连接类型。以下是一个简单的示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
String urlString = "https://www.example.com";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 判断是否为https请求
if (urlString.startsWith("https")) {
// 使用HttpsURLConnection
connection = (HttpsURLConnection) connection;
}
// 设置请求方法
connection.setRequestMethod("GET");
// 获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应内容
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个示例中,我们首先根据URL的协议来判断是否为https请求。如果是https请求,我们将HttpURLConnection转换为HttpsURLConnection。然后,我们设置请求方法(例如GET),并获取响应。最后,我们读取响应内容并输出。
需要注意的是,在使用HttpsURLConnection时,可能需要处理SSL证书验证问题。如果需要信任所有证书,可以使用以下代码:
// 信任所有证书
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; }
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
}
};
// 设置SSL上下文
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
// 设置HttpsURLConnection的SSLSocketFactory
((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
这样,我们就可以在同一个变量中支持HttpURLConnection和HttpsURLConnection了。
领取专属 10元无门槛券
手把手带您无忧上云