gpt4 book ai didi

java - SpringBoot 将 RestTemplateBuilder 从 1.5.14 升级到 2.1.5

转载 作者:行者123 更新时间:2023-12-01 08:27:13 25 4
gpt4 key购买 nike

我的这段代码在使用 RestTemplateBuilder 1.5.14 的项目上运行良好

this.restTemplate = restTemplateBuilder
.setConnectTimeout(connectTimeout)
.setReadTimeout(readTimeout)
.requestFactory(new MyHttpComponentFactoryBuilder()
.build())
.build();

更新到 RestTemplateBuilder 2.1.5 后我有这段代码:
this.restTemplate = restTemplateBuilder
.setConnectTimeout(Duration.ofMillis(connectTimeout))
.setReadTimeout(Duration.ofMillis(readTimeout))
.requestFactory(new MyHttpComponentFactoryBuilder().build().getClass())
.build();

但是在运行代码时我有一个 InvocationTargetException / NullPointerException删除行 .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass()) 时消失, 但调试 new MyHttpComponentFactoryBuilder().build().getClass()不为空

我也尝试过提出的解决方案:
... 
.requestFactory(new MyRequestFactorySupplier())
...

class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

@Override
public ClientHttpRequestFactory get() {

// Using Apache HTTP client.
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
HttpClient httpClient = clientBuilder.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
return requestFactory;
}

}

但我也有 InvocationTargetException / NullPointerException

最佳答案

下面的代码显示了您需要如何为简单案例创建模板。

RestTemplate tmpl = new RestTemplateBuilder().setConnectTimeout(Duration.ofMillis(200))
.setReadTimeout(Duration.ofMillis(100))
.requestFactory(org.springframework.http.client.SimpleClientHttpRequestFactory.class)
.build();

最好能提供 MyHttpComponentFactoryBuilder的源代码类(class)。但我的建议是创建一个类 MyHttpComponentFactory扩展 SimpleClientHttpRequestFactory class 从 MyHttpComponentFactoryBuilder 迁移您的代码到它。

关于java - SpringBoot 将 RestTemplateBuilder 从 1.5.14 升级到 2.1.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61976056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com