使用Spring Boot HTTP Client

发布时间:2023-05-19

Spring Boot HTTP Client 使用指南

一、简介

Spring Boot HTTP Client是Spring Boot提供的一个HTTP客户端库,用来简化HTTP请求的发送和处理。不需要额外添加第三方库,只需要在pom.xml中添加Spring Boot HTTP Client的依赖,就可以使用它来发送HTTP请求。Spring Boot HTTP Client基于Apache HttpClient进行封装,提供了更简洁的API和更易于使用的配置。 为了更好的体验,本文将针对Spring Boot HTTP Client在使用和配置方面进行详细介绍。

二、发送GET请求

发送GET请求是HTTP请求中最简单的一种操作,使用Spring Boot HTTP Client也非常方便。 首先在pom.xml中添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

下面是一个使用Spring Boot HTTP Client发送GET请求的例子:

RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(url, String.class);
System.out.println(result);

其中,RestTemplate是Spring Boot HTTP Client的核心类,用来处理HTTP请求。调用getForObject()方法可以发送GET请求,并返回响应体。传入的两个参数为请求地址和响应体类型。

三、发送POST请求

发送POST请求和GET请求类似,但需要在发送请求前设置请求体内容。以下是使用Spring Boot HTTP Client发送POST请求的例子:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject request = new JSONObject();
request.put("username", "test");
request.put("password", "123456");
HttpEntity<String> httpEntity = new HttpEntity<>(request.toString(), headers);
String result = restTemplate.postForObject(url, httpEntity, String.class);
System.out.println(result);

首先设置请求头信息,然后用JSONObject构造请求体内容,并将请求体和请求头封装在HttpEntity中,最后使用RestTemplate发送POST请求,并返回响应体。

四、添加拦截器

Spring Boot HTTP Client支持添加拦截器,在请求发送和响应处理的过程中,可以对请求和响应进行统一的处理。 下面是添加拦截器的例子:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList(new LoggingClientHttpRequestInterceptor()));

只需要将拦截器添加到RestTemplate的拦截器列表中即可,以下是LoggingClientHttpRequestInterceptor的实现:

public class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        log.info("===========================request begin===========================");
        log.info("URI: {}", request.getURI());
        log.info("Method: {}", request.getMethod());
        log.info("Headers: {}", request.getHeaders());
        log.info("Request body: {}", new String(body, StandardCharsets.UTF_8));
        log.info("============================request end============================");
        ClientHttpResponse response = execution.execute(request, body);
        log.info("===========================response begin==========================");
        log.info("Status code: {}", response.getStatusCode());
        log.info("Status text: {}", response.getStatusText());
        log.info("Headers: {}", response.getHeaders());
        log.info("Response body: {}", StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8));
        log.info("============================response end=============================");
        return response;
    }
}

LoggingClientHttpRequestInterceptor实现了ClientHttpRequestInterceptor接口,可以在拦截请求和响应时输出日志信息。

五、配置连接池

Spring Boot HTTP Client默认使用了连接池技术,可以复用HTTP连接,提高性能。 下面是配置连接池的例子:

public class HttpClientConfig {
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
                .setMaxConnTotal(30)
                .setMaxConnPerRoute(10);
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
        restTemplateBuilder = restTemplateBuilder.requestFactory(() -> requestFactory);
        return restTemplateBuilder.build();
    }
}

以上代码将配置了连接池的RestTemplate注入Spring容器,并设置了最大连接数和每个路由最大连接数。

六、结语

本文介绍了Spring Boot HTTP Client的使用和配置方法,包括发送GET请求和POST请求、添加拦截器和配置连接池等。Spring Boot HTTP Client使用非常简单,可以大幅提高HTTP请求的开发效率,让开发者更加专注于业务逻辑的实现。