HttpURLConnection发送http、https请求
时间: 2024-01-04 07:23:56 浏览: 77
HttpURLConnection是Java标准库提供的用于发送HTTP和HTTPS请求的类,可以用来获取Web资源,以及与服务器进行通信。下面是发送HTTP和HTTPS请求的示例代码:
### 发送HTTP请求
```java
import java.net.*;
import java.io.*;
public class HttpURLConnectionDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.example.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
```
### 发送HTTPS请求
```java
import java.net.*;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpsURLConnectionDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com/");
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
private static class NullHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
private static class NullTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
```
需要注意的是,发送HTTPS请求时需要进行证书验证,但这里我们使用了一个自定义的NullTrustManager类,它不对证书进行任何验证。在实际应用中,不建议使用这种方式,应该使用正确的证书验证机制来保证通信的安全性。
阅读全文