java https请求
时间: 2023-09-12 18:09:28 浏览: 51
以下是一个Java HTTPS请求示例:
```
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class HttpsUtil {
public static void main(String[] args) throws Exception {
// 创建SSLContext对象,用于信任所有证书
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}}, new java.security.SecureRandom());
// 打开连接
URL obj = new URL("https://www.example.com");
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setSSLSocketFactory(sslContext.getSocketFactory());
// 设置请求头
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
```
这个示例中,我们使用了一个自定义的TrustManager来信任所有证书。在实际使用中,为了安全起见,应该使用更加严格的证书验证方式。另外,我们使用了一个简单的GET请求来演示,如果需要使用POST请求,可以使用con.setRequestMethod("POST")来设置。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)