【问题标题】:Spring WebClient get request return "Connection refused: localhost/"Spring WebClient 获取请求返回“连接被拒绝:localhost/”
【发布时间】:2020-04-16 15:53:53
【问题描述】:

当我尝试使用 WebClient 发送 GET 请求时,我收到错误 io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection denied: localhost/

的响应

* WebClient 初始化 *

//hostname = "localhost/127.0.0.1:8081"
//contextPath = "user-service"

    @Bean
    public WebClient userWebclient(@Value("${service.user.hostname}") final String hostname,
                                  @Value("${service.user.contextPath}") final String contextPath) {
        return WebClient
                .builder()
                .baseUrl(hostname + contextPath)
                .build();
    }

* 控制器 *

    private final WebClient userWebclient;

    @GetMapping(value = "/user/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Mono<String> getUserById(@NotNull @PathVariable String userId) {
        userWebclient.

        return userWebclient.get()
               .uri("/UserMock/user/" + userId)
               .header("Accept", "application/json")
               .header("Authorization", "Bearer =........")
               .exchange()
               .flatMap(response -> response.bodyToMono(String.class));
    }

错误信息

io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: localhost/127.0.0.1:8081
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:327)
    at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:665)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:612)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:529)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:491)
    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:905)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
    ... 10 common frames omitted

【问题讨论】:

    标签: java spring-boot spring-webflux


    【解决方案1】:

    在主机中使用任一

    hostname = "localhost:8081" 
    

    或

    hostname = "127.0.0.1:8081"
    

    代替

    hostname = "localhost/127.0.0.1:8081"
    

    【讨论】:

      【解决方案2】:

      检查您的地址是否正确,此错误可能是因为您的端口号不正确,如 8081,但应该是 8080

      【讨论】:

      • 废话!没错,我的端口不对,应该是8181。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 2020-10-11
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      相关资源
      最近更新 更多