apache httpclient 4 范例
时间: 2024-04-27 13:20:12 浏览: 73
httpclient 例子
以下是使用 Apache HttpClient 4 发送 HTTP GET 请求的示例代码:
```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 HttpGetExample {
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) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
}
}
```
以上代码使用 HttpClients.createDefault() 创建一个默认的 CloseableHttpClient 对象,然后使用 HttpGet 发送一个 GET 请求到指定的 URL。接着,利用 try-with-resources 语句自动关闭 CloseableHttpResponse 对象。在 try-with-resources 代码块中,使用 response.getEntity() 获取响应的实体,并将其转换为字符串。最后,输出响应的字符串结果。
阅读全文