apache httpclient发送http和https请求代码
时间: 2024-01-04 21:39:46 浏览: 160
httpclient发送post请求实现代码
以下是使用 Apache HttpClient 发送 HTTP 和 HTTPS 请求的示例代码:
1. 发送 HTTP 请求
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // 打印响应状态码
}
}
```
2. 发送 HTTPS 请求
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.SSLContext;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true)
.build();
HttpClient httpClient = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpGet httpGet = new HttpGet("https://www.example.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // 打印响应状态码
}
}
```
注意事项:
- HTTPS 请求需要设置 SSLContext 和 SSLHostnameVerifier;
- SSLContext 的 TrustManager 应该接受所有证书,这不安全,建议修改为验证证书;
- SSLHostnameVerifier 应该使用严格的 HostnameVerifier,这里为了简单只使用了 NoopHostnameVerifier。
阅读全文