java httpclient 接口_Java利用httpclient通过get调用接口
时间: 2023-11-28 21:04:35 浏览: 91
JAVA利用HttpClient进行HTTPS接口调用
4星 · 用户满意度95%
使用Apache HttpClient库可以很方便地在Java中完成HTTP请求。下面是一个示例代码,演示如何使用HttpClient库通过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;
public class HttpClientDemo {
public static void main(String[] args) {
String url = "https://example.com/api/getData";
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这段代码首先创建了一个`CloseableHttpClient`对象。然后使用`HttpGet`对象来设置请求的URL,最后使用`httpclient.execute()`方法来执行请求。如果请求成功,就可以通过`response.getEntity()`方法获取响应的实体,并使用`EntityUtils.toString()`方法将其转换为字符串,最后输出到控制台。
阅读全文