HttpClient可以以多种方式发送GET请求,以下是其中的一种示例代码:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientGetExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); String url = "https://example.com/api"; try { HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity); System.out.println(result); } } catch (Exception e) { e.printStackTrace(); } } }
在这个示例中,我们首先创建了一个HttpClient
实例,然后构造了一个HttpGet
请求,并指定了请求的URL。然后使用httpClient.execute(request)
方法发送GET请求,并获取响应。最后,通过EntityUtils.toString(entity)
方法将响应的内容转换为字符串并进行输出。
需要注意的是,在使用HttpClient发送GET请求之前,需要确保你的项目中已经引入了HttpClient的相关依赖。