Spring RestTemplate Behavior when handling responses with a status of NO_CONTENT

前端 未结 6 1720
小蘑菇
小蘑菇 2020-12-08 11:05

Okay, I have a class NamedSystems, that has as its only field a Set of NamedSystem.

I have a method to find NamedSystems by certain criteria. That\'s not really imp

6条回答
  •  悲&欢浪女
    2020-12-08 11:59

    I believe you should probably look at the ResponseExtractor interface & call execute on the RestTemplate providing your implementation of the extractor. To me it looks like a common requirement to do this so have logged this:

    https://jira.springsource.org/browse/SPR-8016

    Here's one I prepared earlier:

    private class MyResponseExtractor extends HttpMessageConverterExtractor {
    
        public MyResponseExtractor (Class responseType,
          List> messageConverters) {
            super(responseType, messageConverters);
        }
    
        @Override
        public MyEntity extractData(ClientHttpResponse response) throws IOException {
    
            MyEntity result;
    
            if (response.getStatusCode() == HttpStatus.OK) {
                result = super.extractData(response);
            } else {
                result = null;
            }
    
            return result;
        }
    }
    

    I've tested this & it seems to do what I want.

    To create the instance of the ResponseExtractor I call the constructor & pass the converters from a RestTemplate instance that's been injected;

    E.g.

    ResponseExtractor responseExtractor =
        new MyResponseExtractor(MyEntity.class, restTemplate.getMessageConverters());
    

    Then the call is:

    MyEntity responseAsEntity =
        restTemplate.execute(urlToCall, HttpMethod.GET, null, responseExtractor);
    

    Your mileage may vary. ;-)

提交回复
热议问题