我正在尝试创建一个 Spring WebClient 来调用 REST API。为此,我编写了以下代码。
@Bean
public WebClient defaultWebClient() {
var tcpClient = TcpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3_000)
.doOnConnected(connection ->
connection.addHandlerLast(new ReadTimeoutHandler(3))
.addHandlerLast(new WriteTimeoutHandler(3)));
return WebClient.builder()
.baseUrl("https://test.com")
.clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
.defaultHeader(HttpHeaders.ACCEPT, "application/vnd.api+json")
.build();
}
然后是带有以下代码的实际 URI。
String user = webClient
.get()
.uri(URI.create("/api/v1/user/1"))
.header("Authorization", TOKEN)
.header(HttpHeaders.ACCEPT, "application/json")
.retrieve()
.bodyToMono(String.class)
.block();
但是当上面的代码执行时,它会抛出以下异常。
{"timestamp":"1608209276546","level":"ERROR","thread":"http-nio-8080-exec-1","mdc":{"tenantId":null},"logger":"org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet]","message":"Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.reactive.function.client.WebClientRequestException: Connection refused: no further information: /127.0.0.1:12012; nested exception is io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: /127.0.0.1:12012] with root cause","context":"default","exception":"java.net.ConnectException: Connection refused: no further information\r\n\tat java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)\r\n\tat
我不确定我需要在这里更改哪里,以便它开始指向基本 URI 而不是本地主机 (127.0.0.1:12012)。 另一件事是,如果我在 API 调用中传递了完全限定名称 ( https://test.com/api/v1/user/1),那么它就可以正常工作。
最佳答案
来自 javadoc,方法 uri(URI uri)
Specify the URI using an absolute, fully constructed URI
所以这个版本的方法不使用配置中的基本 url。
相反,您应该使用 UriBuilder 指定 URI,它被注入(inject)到方法 uri(Function<UriBuilder,URI> uriFunction) 中.
String user = webClient
.get()
.uri(uriBuilder -> uriBuilder.path("/api/v1/user/1").build())
...
关于java - 如何将基本 URI 设置为 Spring WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65341166/