使用Spring Rest Template调用Rest Web服务,如下所示 -
ResponseEntity<String> response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, String.class);
并以String格式获取输出
<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类时,如下所示
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
}
如果Response http代码为500,则响应不是info类型,而是其他类型的infoException。
我们可以指定resttemplate根据Http响应代码解组输出吗?
答案 0 :(得分:2)
其余模板在提取数据之前检查错误响应。因此,一种方法是使用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;
}
答案 1 :(得分:1)
Spring 5专门为此目的提供ExtractingResponseErrorHandler
答案 2 :(得分:0)
由于从XML到类的映射,它的XML到POJO无法反序列化。尝试使用此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
}