3

再会。

我正在 Spring 上编写 REST 客户端。服务器可以发送一个 XML 或 JSON 编组对象作为响应。在正常请求/响应的情况下,它可以正常工作。我的 RestTemplate 客户端可以解组响应。但是如果出现 404 错误,服务器会将错误描述符作为 XML/JSON 发送到响应正文中。

我不知道如何解组错误请求正文。

这是我的 REST 客户端代码:

@Service
public class XsdClientImpl implements InitializingBean, XsdClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(XsdClientImpl.class);
    @Autowired
    @Qualifier("xsdClientRestTemplate")
    private RestTemplate restTemplate;
    private String baseUrl;

    @Override
    public XsdInfoType fetchNamespace(String namespace) throws XsdClientException {
        Map<String, String> vars = Collections.singletonMap("namespace", namespace);
        try {
            return restTemplate.getForObject(baseUrl + "/xsd/get/{namespace}.xml", XsdInfoType.class, vars);
        } catch (final HttpClientErrorException e) {
            // e.getResponseBodyAsByteArray() how to unmarshall it? it can be XML or JSON
            return null;
        }
    }
}

这是 Spring 配置的片段:

<bean id="objectMapper"
      class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:indentOutput="true" p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ">
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" p:targetObject-ref="objectMapper" p:targetMethod="registerModule">
    <property name="arguments">
        <list>
            <bean class="com.fasterxml.jackson.datatype.joda.JodaModule"/>
        </list>
    </property>
</bean>

<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="jaxb2RootElementHttpMessageConverter" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
<bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    <property name="objectMapper" ref="objectMapper"/>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="classpath:xsd-client.properties"/>

<bean class="org.springframework.web.client.RestTemplate" id="xsdClientRestTemplate">
    <property name="messageConverters">
        <list>
            <ref bean="mappingJackson2HttpMessageConverter"/>
            <ref bean="jaxb2RootElementHttpMessageConverter"/>
        </list>
    </property>
</bean>

注意:在正常情况下,REST 服务器发送 XsdInfoType 编组对象。但是错误响应对象有其他类型。

4

1 回答 1

1

成子的RestTemplate我们可以这样做:

HttpMessageConverterExtractor responseExtractor = new HttpMessageConverterExtractor<>(YourErrorType.class, getMessageConverters());
YourErrorType yet = (YourErrorType) responseExtractor.extractData(new ClientHttpResponse(e) {
    // TODO Implement interface. It is very simple.
    // You can get all data from the `e' variable.
    // But I think the Spring has own implementation.
});
于 2013-08-13T15:12:44.780 回答