Reactive WebClient GET Request with text/html response

前端 未结 2 2184
无人及你
无人及你 2021-01-06 04:38

Currently I’m having an issue with new Spring 5 WebClient and I need some help to sort it out. The issue is:

I request some url that returns json respons

2条回答
  •  Happy的楠姐
    2021-01-06 05:28

    Having a service send JSON with a "text/html" Content-Type is rather unusual.

    There are two ways to deal with this:

    1. configure the Jackson decoder to decode "text/html" content as well; look into the WebClient.builder().exchangeStrategies(ExchangeStrategies) setup method
    2. change the "Content-Type" response header on the fly

    Here's a proposal for the second solution:

    WebClient client = WebClient.builder().filter((request, next) -> next.exchange(request)
                    .map(response -> {
                        MyClientHttpResponseDecorator decorated = new 
                            MyClientHttpResponseDecorator(response); 
                        return decorated;
                    })).build();
    
    class MyClientHttpResponseDecorator extends ClientHttpResponseDecorator {
    
      private final HttpHeaders httpHeaders;
    
      public MyClientHttpResponseDecorator(ClientHttpResponse delegate) {
        super(delegate);
        this.httpHeaders = new HttpHeaders(this.getDelegate().getHeaders());
        // mutate the content-type header when necessary
      }
    
      @Override
      public HttpHeaders getHeaders() {
        return this.httpHeaders;
      }
    }
    

    Note that you should only use that client in that context (for this host). I'd strongly suggest to try and fix that strange content-type returned by the server, if you can.

提交回复
热议问题