在 Spring Boot 3 中使用 RestTemplate 获取带有 Body 的请求

问题描述 投票:0回答:1

我想在 Spring Boot 3 中通过

RestTemplate

发送带有请求正文的 GET 请求 注意 - 单独使用
exchange(URI, HttpMethod.GET, HttpEntity(with_the_body_set), ...)
不起作用
大多数在线资源(例如this)都是针对Spring Boot 2,我相信它使用了httpclient v4
但是,我使用的是 Spring Boot 3,它使用 httpclient v5
我怎样才能通过 -
RestTemplate
(首选)或通过
HttpClient
(最后手段)实现这一目标?

注意 - 我知道这很可怕,但我是这里的客户端,无法控制服务器

java spring spring-boot httpclient apache-httpclient-5.x
1个回答
0
投票

Http 请求不能包含 GET 方法的请求正文。 这背后的基本思想是客户端向服务器请求特定类型的数据,例如 findByX() 调用。 有人可能会说,如果要发送的数据取决于某种类型的条件怎么办? 这是绝对有可能的。在这些情况下,客户端应发送条件数据以包含在 URI 或请求查询参数中。

MDN 文档参考相同:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET

话虽如此,我理解您的担忧。有时,对于使用不再维护的外部依赖项或不遵循正确的设计原则的开发人员来说,这是可怕的。

这是我可以想出的一些与休息客户端一起工作的配置,它对于带有请求正文的 GET 请求运行良好。请随意根据您的需要进行修改。

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


public class RestClientConfig {

    private final RestTemplate restTemplate;

    public RestClientConfig() {
        restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    }

    public String getWithBody(Object requestBody) {

        return restTemplate.exchange("http://localhost:7070/test-url", HttpMethod.GET, new HttpEntity<>(requestBody), String.class).getBody();

    }

}

和apache客户端依赖:

<dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.3.1</version>
</dependency>

用于测试的控制器代码:

@GetMapping("/test-get-request-with-request-body")
public ResponseEntity<Object> testGetWithRequestBody(@RequestBody Object body) {
    RestClientConfig restClientConfig = new RestClientConfig();
    return new ResponseEntity<>(restClientConfig.getWithBody(body), HttpStatus.OK);
}

@GetMapping("/test-url")
public ResponseEntity<Object> testGetWithRequestBody2(@RequestBody Object body) {
    String response = "[" + body.toString().concat(",").concat(body.toString()) + "]";
    System.out.println(response);
    return new ResponseEntity<>(response, HttpStatus.OK);
}

希望有帮助!!

© www.soinside.com 2019 - 2024. All rights reserved.