我有一个带有Spring框架的Java 8应用程序。我们需要从应用程序中使用REST调用补丁操作。
代码段如下:
import com.xyz.myobject.ResponseAdmission;
import com.xyz.myobject.RequestAdmission;
@Repository
public class AdmissionRepository {
@Autowired
private RestTemplate restTemplate;
public ResponseObject updateAdmission(RequestAdmission requestAdmission, String admissionId) {
UriBuilder uriBuilder = UriBuilder.fromUri("https://admissionportal.com").path("admission").path("admissionId="+admissionId);
HttpEntity<RequestAdmission> admissionEntity = new HttpEntity<>(requestAdmission, this.getHeaders);
ResponseEntity<ResponseAdmission> responseEntity = this.restServiceESBSupport.exchange(uriBuilder.build(), HttpMethod.PATCH, admissionEntity , ResponseAdmission.class);
return responseEntity.getBody();
}
public MultiValueMap<String, String> getHeaders() {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Accept", "application/xml");
headers.add("Content-Type", "application/xml");
return headers;
}
}
当我执行上面的代码时,当执行带有'exchange'关键字的行时,它会给出错误消息:
org.springframework.web.client.RestClientException:无法写入请求:找不到用于请求类型[com.xyz.myobject.RequestAdmission]和内容类型[application / xml]的合适的HttpMessageConverter < / p>
当我调试代码时,restTemplate已注册了以下7个转换器:
ByteArrayHttpMessageConverter,
StringHttpMessageConverter,
ResourceHttpMessageConverter,
SourceHttpMessageConverter,
AllEncompassingFormHttpMessageConverter,
Jaxb2RootElementHttpMessageConverter,
MappingJackson2HttpMessageConverter
我还尝试添加以下行:
this.restTemplate.getMessageConverters().add(new Jaxb2RootElementHttpMessageConverter());
但仍然无法正常工作。
RequestAdmission和ResponseAdmission是从xsds生成的JAXB POJO对象。
Web服务接受xml形式的请求,响应也采用xml形式。
请告知。
答案 0 :(得分:0)
您可以将自己的XML创建为字符串,并在您的请求中使用它,如下所示:
@Repository
public class AdmissionRepository {
@Autowired
private RestTemplate restTemplate;
public ResponseObject updateAdmission(RequestAdmission requestAdmission, String admissionId) {
UriBuilder uriBuilder = UriBuilder.fromUri("https://admissionportal.com").path("admission").path("admissionId="+admissionId);
String xmlString = // create an actual valid XML string with all the <tag>value</tag> and the whole structure.
HttpEntity<String> admissionEntity = new HttpEntity<>(xmlString, this.getHeaders);
ResponseEntity<ResponseAdmission> responseEntity = this.restServiceESBSupport.exchange(uriBuilder.build(), HttpMethod.PATCH, admissionEntity , ResponseAdmission.class);
return responseEntity.getBody();
}