使用Spring Boot中的HttpClient发送HTTP请求,可以按照以下步骤进行:
- 添加HttpClient依赖
在pom.xml
文件中添加以下依赖:
1 2 3 4
| <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency>
|
- 创建HttpClient实例
创建HttpClient实例的方式有多种,其中比较常见的是通过HttpClientBuilder
类创建:
1
| CloseableHttpClient httpClient = HttpClientBuilder.create().build();
|
- 创建HttpRequest对象
根据需要发送的请求类型(GET、POST等),创建相应的HttpRequest对象。可以使用HttpUriRequest
的子类,如HttpGet
、HttpPost
等。
例如,创建一个GET请求:
1
| HttpGet request = new HttpGet("http://example.com");
|
- 发送请求并获取响应
使用httpClient.execute()
方法发送请求,并返回CloseableHttpResponse
对象,该对象包含响应信息。可以使用getStatusLine()
获取响应状态码,使用getEntity()
获取响应主体。
例如,发送请求并获取响应:
1 2 3 4
| CloseableHttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity, "UTF-8");
|
- 关闭HttpClient和HttpResponse
完成请求后,需要关闭HttpClient和HttpResponse对象,释放资源。
例如,在finally块中关闭HttpClient和HttpResponse对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| try { // 发送请求并获取响应 } finally { try { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } catch (IOException e) { // 忽略异常 } }
|
阅读剩下更多