HttpClient是一个功能强大、开源的HTTP客户端库,可以用于发送HTTP请求和处理HTTP响应。使用HttpClient的Get方式发送请求需要以下步骤:
创建HttpClient对象:CloseableHttpClient httpClient = HttpClients.createDefault();
创建HttpGet对象,并设置请求的URL:HttpGet httpGet = new HttpGet("http://example.com/api/resource");
执行请求并获取响应:CloseableHttpResponse response = httpClient.execute(httpGet);
获取响应的状态码:int statusCode = response.getStatusLine().getStatusCode();
获取响应的内容:HttpEntity entity = response.getEntity();String responseContent = EntityUtils.toString(entity, "UTF-8");
关闭HttpClient和响应:response.close();httpClient.close();
完整的示例代码如下:
import java.io.IOException;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 HttpClientExample {public static void main(String[] args) {CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpGet = new HttpGet("http://example.com/api/resource");try {CloseableHttpResponse response = httpClient.execute(httpGet);try {int statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();String responseContent = EntityUtils.toString(entity, "UTF-8");System.out.println("Status Code: " + statusCode);System.out.println("Response Content: " + responseContent);} finally {response.close();}} catch (IOException e) {e.printStackTrace();} finally {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}}
以上代码会发送一个GET请求到"http://example.com/api/resource",并输出响应的状态码和内容。请注意,这里的示例代码没有处理异常情况,实际使用中需要进行异常处理。