java httpclient 代码
时间: 2023-10-17 10:58:43 浏览: 84
httpclient代码
以下是使用Java HttpClient发送HTTP请求的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
}
}
```
使用HttpClient发送HTTP请求的基本步骤如下:
1. 创建一个 CloseableHttpClient 对象,通常使用 HttpClients.createDefault() 方法创建;
2. 创建一个 HttpGet 或者 HttpPost 对象,设置请求 URL 和请求参数;
3. 使用 CloseableHttpClient 对象执行请求,得到一个 CloseableHttpResponse 对象;
4. 从 CloseableHttpResponse 对象中获取响应内容。
阅读全文