httpclient get请求java
时间: 2023-09-07 16:16:54 浏览: 108
您可以使用 Apache HttpClient 库来发送 GET 请求。以下是一个示例代码:
```java
import org.apache.http.HttpEntity;
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;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,我们首先创建一个 `CloseableHttpClient` 对象,然后使用 `HttpGet` 类来创建一个 GET 请求对象,并将目标 URL 传递给构造函数。接下来,我们使用 `httpClient.execute(httpGet)` 发送请求,并获取响应对象。通过检查响应对象的实体是否为空,
阅读全文