问题描述
按如下所示使用Spring Rest模板调用Rest Web服务-
Calling a Rest Webservice using the Spring Rest Template as follows-
ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, String.class);
并以String格式获取输出
and get the output in String format as
<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类时
When trying to unmarshal it to java class as follows
ResponseEntity<Info> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, Info.class)
Info类定义为
@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,则响应不是info类型,而是其他infoException类型.
If the Response http code is 500 then the response is not of type info but of other type infoException.
我们能否指定resttemplate来根据Http响应代码解组输出?
Can we specify to the resttemplate to unmarshal the output depending on the Http response code?
推荐答案
其余模板在提取数据之前检查响应是否有错误.因此,一种方法是使用 ResponseErrorHandler 并重写handleError方法,以使用转换器将对对象的错误响应提取出来,然后将此错误对象包装为异常.这样的事情.
The rest template checks response for error before extracting the data. So one way would be to create Rest Template with the implementation of ResponseErrorHandler and override the handleError method to extract the error response to your object using converters and then wrap this error object into exception. Something like this.
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 Rest Service调用期间根据HTTP代码解组响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!