HttpsURLConnection
时间: 2023-08-20 14:35:47 浏览: 48
HttpsURLConnection 是 HttpURLConnection 的一个子类,用于在 Java 中进行 https 请求。与 HttpURLConnection 类似,HttpsURLConnection 也提供了对 http 请求的支持,并且可以通过 setRequestMethod() 方法设置请求方法(如 GET、POST 等)。不同的是,HttpsURLConnection 需要进行 SSL/TLS 握手,以确保通信的安全性。
以下是一个简单的示例,演示如何使用 HttpsURLConnection 发送 https 请求:
```java
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class HttpsExample {
public static void main(String[] args) throws Exception {
String httpsUrl = "https://example.com";
URL url = new URL(httpsUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// 可以设置请求方法、超时时间等参数
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
// 打印服务器返回的状态码
System.out.println("Response code: " + con.getResponseCode());
// 读取服务器返回的数据
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
// 打印服务器返回的数据
System.out.println("Response content: " + content.toString());
}
}
```
需要注意的是,在实际使用中,可能需要设置 SSLContext、TrustManager 等参数,以确保 https 请求的安全性。