CloseableHttpClient httpClient = HttpClients.createDefault();
时间: 2024-01-17 19:18:52 浏览: 174
`CloseableHttpClient httpClient = HttpClients.createDefault();`是使用Apache HttpClient库创建一个默认的可关闭的HttpClient对象的代码。这个对象可以用来发送HTTP请求并与服务器进行通信。
这是一个简单的示例代码:
```java
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;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
// 处理响应
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例中,我们创建了一个默认的HttpClient对象,并使用HttpGet方法创建了一个GET请求。然后,我们使用`httpClient.execute(httpGet)`方法发送请求并获取响应。最后,我们可以处理响应,例如打印响应状态行。
阅读全文