举一个java的HttpClient类型例子
时间: 2024-01-31 09:03:41 浏览: 32
以下是一个使用Java的HttpClient发送GET请求的简单例子:
```java
import java.io.IOException;
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("https://www.example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
response.close();
httpClient.close();
}
}
```
在此示例中,我们使用Apache HttpClient库来创建一个默认HttpClient实例。然后,我们创建一个HttpGet对象,将其设置为访问URL为“https://www.example.com”的Web资源。最后,我们执行请求并获取响应主体作为字符串。当我们完成后,关闭响应和HttpClient实例以释放资源。