JavaEar 专注于收集分享传播有价值的技术资料

org.springframework.web.client.HttpClientErrorException: 415 null(Spring Resttemplate)

I try to get list of entity with using rest template, but I get 415 error in line:

ResponseEntity<List<ResponseOrderDto>> responseEntity = rest.exchange

My implementation:

RestTemplate rest = new RestTemplate();
        rest.getInterceptors().add((request, body, execution) -> {
            ClientHttpResponse response = execution.execute(request,body);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            response.getHeaders().add("Bearer", contentToken);
            return response;
        });
        ResponseEntity<List<ResponseOrderDto>> responseEntity = rest.exchange(
                ORDER_SERVICE_URL + "/by-user",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<ResponseOrderDto>>() {
                });

How fix this error?

1个回答

    最佳答案
  1. 415 means unsupported content type, so the Content-type header is not correctly set.

    Based on your code, I think that the request needs JSON Content-Type header, but you set the content-type header on the response instead of the request.

    Change your interceptor to be something like this:

          rest.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            request.getHeaders().add("Bearer", contentToken);
            ClientHttpResponse response = execution.execute(request, body);
            return response;
          });
    

    To set the headers at the right time to the request