httpclient-4.5.13get请求怎么写
时间: 2024-09-27 22:04:22 浏览: 38
httpclient-4.5jar包
HttpClient 4.5.13是一个流行的Java库,用于HTTP客户端操作。以下是使用它发送GET请求的基本步骤:
```java
import org.apache.http.HttpResponse;
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) throws Exception {
// 创建一个httpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 创建HttpGet请求
HttpGet request = new HttpGet("http://example.com/api/resource");
// 发送请求并获取响应
HttpResponse response = httpClient.execute(request);
// 检查状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status Code: " + statusCode);
// 读取响应内容(这里只是示例,实际应用中可能需要解析响应体)
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Response Body: " + responseBody);
} finally {
// 关闭连接以释放资源
httpClient.close();
}
}
}
```
在这个例子中,首先创建了一个`CloseableHttpClient`实例,然后构造一个`HttpGet`对象并设置目标URL。接着执行请求,获取响应,并处理结果。最后别忘了关闭`CloseableHttpClient`以释放网络资源。
阅读全文