我正在使用Spring REST模板从REST服务获取响应。我得到以下异常,但我无法弄清楚问题。请找到以下详细信息。我错过了什么吗?
当我使用邮递员尝试此操作时,我得到了正确的响应。
这里AddFileServerBean是请求:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<AddFileServerBean> requestEntity = new HttpEntity<AddFileServerBean>(addFileServerBean,headers);
ResponseEntity<ResponseObject> response = restTemplate.exchange(endPointUrl, HttpMethod.POST, requestEntity, ResponseObject.class);
例外
Exception in thread "main" java.lang.NoSuchMethodError: org.springframework.util.Assert.noNullElements(Ljava/util/Collection;Ljava/lang/String;)V
at org.springframework.web.client.HttpMessageConverterExtractor.<init>(HttpMessageConverterExtractor.java:77)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.<init>(RestTemplate.java:991)
at org.springframework.web.client.RestTemplate.responseEntityExtractor(RestTemplate.java:822)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:585)
at addfileserver.rest.FileRestTemplate.main(FileRestTemplate.java:280)
HttpMessageConverterExtractor 的源代码
@SuppressWarnings("unchecked")
HttpMessageConverterExtractor(Type responseType, List<HttpMessageConverter<?>> messageConverters, Log logger) {
Assert.notNull(responseType, "'responseType' must not be null");
Assert.notEmpty(messageConverters, "'messageConverters' must not be empty");
Assert.noNullElements(messageConverters, "'messageConverters' must not contain null elements");
this.responseType = responseType;
this.responseClass = (responseType instanceof Class ? (Class<T>) responseType : null);
this.messageConverters = messageConverters;
this.logger = logger;
}
我的预期响应对象
{
"dataObj": {
"responseCode": 0,
"messageList": [
"Test"
],
"values": {
"uniqueId": "Test",
"pwd": "Test"
},
"objectValue": "-"
},
"applicationErrors": null
}
我认为问题是当您尝试将从 REST 端点接收的输出映射到响应对象时。
同样在创建 RestTemplate 实例时,请尝试以下操作:
public RestTemplate getRestTemplateInstance(String baseUri) {
RestTemplate restTemplate = new RestTemplate();
restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
return restTemplate;
}
通过传递 baseUri 来获取 RestTemplate 实例,并调用 REST 终结点。