gpt4 book ai didi

java - RestTemplate 解码错误正文

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:43 27 4
gpt4 key购买 nike

美好的一天。

我正在 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 编码对象。但是错误响应对象有其他类型。

最佳答案

进入 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.
});

关于java - RestTemplate 解码错误正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17236642/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com