【发布时间】:2016-07-20 12:23:53
【问题描述】:
我正在尝试使用 RestTemplate 对服务进行简单的 POST。我拥有的 XSD 不会生成根元素,而是具有根元素类型。但是 ObjectFactory.createFoo(FooType) 给了我试图发布的 JAXBElement,但没有这样做,但出现以下异常:
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [com.foo.FooType] and content type [application/xml]
这是我调用其余服务的代码
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity<FooType> entity = new HttpEntity<FooType>(request.getValue(),headers);
JAXBElement<ResponseType> response = restTemplate.postForObject(esbReplaceNumberListURI, entity, JAXBElement.class);
在通过 StackOverflow 中的答案后,我尝试将 Jaxb2Marshaller(of Spring O/X jar ) 添加到 RestTemplate,并将 setSupportJaxbElementClass 设置为 true。这没有帮助。
我正在构建我的请求对象,如下所示,它给了我 JAXBElement
JAXBElement<FooType> request = ObjectFactory.createFoo(FooType);
然后在发布时我执行 request.getValue() 如下:
HttpEntity<FooType> entity = new HttpEntity<FooType>(request.getValue(),headers);
我的 Spring 配置如下:
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(getMarshallingHttpMessageConverter());
return restTemplate;
}
@Bean
public MarshallingHttpMessageConverter getMarshallingHttpMessageConverter() {
MarshallingHttpMessageConverter marshallingConverter = new MarshallingHttpMessageConverter();
marshallingConverter.setMarshaller(jaxb2Marshaller());
marshallingConverter.setUnmarshaller(jaxb2Marshaller());
marshallingConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML, MediaType.TEXT_XML));
return marshallingConverter;
}
@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setSupportJaxbElementClass(Boolean.TRUE);
marshaller.setPackagesToScan("com.foo.domain.*");
return marshaller;
}
使用 Spring-Boot 1.3.5.RELEASE,而后者又使用 Spring 4.2.6.RELEASE。 我无法解决这个问题。非常感谢任何帮助。
【问题讨论】:
标签: spring resttemplate jaxb2