阅读量:7
HttpClient 是一个开源的Java HTTP客户端库,用于发送HTTP请求和处理响应。
以下是使用HttpClient的基本步骤:
导入HttpClient库。
import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils;
创建HttpClient实例。
HttpClient httpClient = HttpClientBuilder.create().build();
创建HTTP请求对象,如HttpGet或HttpPost。
HttpGet httpGet = new HttpGet("http://www.example.com"); HttpPost httpPost = new HttpPost("http://www.example.com");
发送HTTP请求并获取响应。
CloseableHttpResponse response = httpClient.execute(httpGet);
处理响应。
int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity());
关闭响应和HttpClient。
response.close(); httpClient.close();
以上是基本的使用方法,你可以根据需求进行更多的操作,如添加请求头、设置请求参数等。