根据 Spring 休息服务调用期间的 HTTP 代码解组响应

Unmarshalling response depending on HTTP code during Spring Rest Service call

使用 Spring Rest 模板调用 Rest Web 服务,如下所示-

ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, String.class); 

并得到字符串格式的输出

<Info xmlns="http://schemas.test.org/2009/09/Tests.new" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<FirstName>FirstName</FirstName>
<LastName>LastName</LastName>
<TestGuid>Guid</TestGuid>
<TestUID>1</TestUID>
<Token>token</Token>
<TestUserID>14</TestUserID>
</Info>

当尝试将其解组为 java class 时,如下所示

ResponseEntity<Info> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, Info.class)

信息 class 定义为

@XmlRootElement(name = "Info", namespace = "http://schemas.test.org/2009/09/Tests.new")
public class Info implements Serializable{

    private String FirstName;
    private String LastName;
    private String TestGuid;
    private String TestUID;
    private String Token;
    private String TestUserID;

    //getters and setter

}   

如果响应 http 代码为 500,则响应不是信息类型而是其他类型的 infoException。

我们能否指定 resttemplate 根据 Http 响应代码解组输出?

它的 XML 到 POJO 由于从 XML 映射到 class 无法反序列化。尝试使用这个 POJO。

public class Info implements Serializable{

    private String TestGuid;

    private String TestUID;

    private String FirstName;

    private String xmlns;

    private String Token;

    private String LastName;

    private String TestUserID;

    //getters and setter
}

其余模板在提取数据之前检查响应是否有错误。因此,一种方法是使用 ResponseErrorHandler 的实现创建 Rest 模板,并覆盖 handleError 方法以使用转换器提取对对象的错误响应,然后将此错误对象包装到异常中。像这样的东西。

    class ErrorObjectResponseHandler implements ResponseErrorHandler {

      private List<HttpMessageConverter<?>> messageConverters;

      @Override
      public boolean hasError(ClientHttpResponse response) throws IOException {
        return hasError(response.getStatusCode());
      }

      protected boolean hasError(HttpStatus statusCode) {
        return (statusCode.is4xxClientError() || statusCode.is5xxServerError());
      }

      @Override
      public void handleError(ClientHttpResponse response) throws IOException {
        HttpMessageConverterExtractor<Error> errorMessageExtractor =
          new HttpMessageConverterExtractor(Error.class, messageConverters);
        Error errorObject = errorMessageExtractor.extractData(response);
        throw new SomeException(errorObject);
      }

      public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        this.messageConverters = messageConverters;
      }

Spring 5 个报价ExtractingResponseErrorHandler 专门为此目的