【发布时间】:2020-01-02 12:28:39
【问题描述】:
我有一个使用 JSON 作为交换数据格式的 Spring Boot 应用程序。现在我必须添加一个仅以 xml 发送数据的服务。我在我的 pom 中添加了jackson-dataformat-xml,它运行良好。
@Service
public class TemplateService {
private final RestTemplate restTemplate;
private final String serviceUri;
public TemplateService (RestTemplate restTemplate, @Value("${service.url_templates}") String serviceUri) {
this.restTemplate = restTemplate;
this.serviceUri = serviceUri;
}
public boolean createTemplate(Template template) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity entity = new HttpEntity<>(template, headers);
ResponseEntity<Template> response = restTemplate.exchange(serviceUri, HttpMethod.POST, entity, Template.class);
if (response.getStatusCode().is2xxSuccessful()) {
// do some stuff
return true;
}
return false;
}
}
现在不幸的是,在添加了依赖项之后,我的所有其他 POST 方法都默认发送 XML。或者Content 设置为application/xml。但我想在这里有JSON。
@Service
public class SomeOtherService{
private final RestTemplate restTemplate;
private final String anotherUri;
public SomeOtherService(RestTemplate restTemplate, @Value("${anotherUri.url}") String anotherUri) {
this.restTemplate = restTemplate;
this.anotherUri = anotherUri;
}
public ComponentEntity doSomething(String projectId, MyNewComponent newComponent) {
ResponseEntity<MyNewComponent> result = this.restTemplate.exchange(anotherUri ,HttpMethod.POST, new HttpEntity<>(newComponent), MyNewComponent.class);
//...
}
}
我没有明确设置标头,因为有很多 POST 请求,我不想全部更改。有没有办法将 default Content 设置为 JSON?
到目前为止我尝试过
- 添加拦截器。但有时我需要有 XML。
- 覆盖内容协商
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
- 设置
restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter()));
并在我想要 XML 的服务中使用 new RestTemplate()。
==> 3 号确实有效,但感觉有点不对。
我希望在某处设置默认的 Content 类型,以便在没有设置任何内容的正常情况下使用 JSON,在我将 Content 显式设置为 XML 的情况下使用 XML。
感谢您的帮助。
【问题讨论】:
标签: java spring-boot jackson-databind jackson-dataformat-xml