我有一个工作的 Spring Boot 应用程序,它使用 JSON 作为交换数据格式。现在我必须添加一个仅以 xml 形式发送数据的服务。我添加了jackson-dataformat-xml
到我的 pom ,效果很好。
@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);
}
- setting
restTemplate.setMessageConverters(Collections.singletonList(new MappingJackson2HttpMessageConverter()));
并使用new RestTemplate()
在我想要 XML 的服务中。
==> 第三个确实有效,但感觉有点不对。
我本来希望设置默认值Content
在某处键入,以便在未设置任何内容的正常情况下使用 JSON,在我显式设置的情况下使用 XMLContent
to XML.
谢谢你的帮助。