jdk17怎么使用CloseableHttpClient
时间: 2023-12-19 19:29:42 浏览: 166
以下是使用CloseableHttpClient发送HTTP请求的示例代码:
```java
import java.io.IOException;
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;
public class HttpClientExample {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
} finally {
response.close();
}
}
}
```
在这个示例中,我们首先创建了一个CloseableHttpClient对象,然后创建了一个HttpGet对象,设置了请求的URL。接下来,我们使用httpClient.execute方法发送请求,并获取响应。最后,我们从响应中获取实体,并将其转换为字符串输出。
需要注意的是,在使用CloseableHttpClient发送请求后,我们需要手动关闭响应对象,以释放资源。
阅读全文