我有Spring RestTemplate的问题,我尝试从返回JSON的地址获取数据。当我使用RestTemplate.getObjectFor(String url,Class responseType)时,我得到了关于无法读取文档的异常:意外字符('<'(代码60))。但是,如果我使用RestTemplate.getObjectFor(URI url,Class responseType),那么它可以工作!
谁能告诉我为什么会这样?
以下是休息模板
的配置 @Bean(name = "cernerRestTemplate")
public RestTemplate cernerRestTemplate() throws NoSuchAlgorithmException {
RestTemplate cernerRestTemplate = new RestTemplate();
cernerRestTemplate.setRequestFactory(getHttpComponentsClientHttpRequestFactory());
cernerRestTemplate.setMessageConverters(getMessageConverters());
cernerRestTemplate.setInterceptors(getInterceptors());
return cernerRestTemplate
}
private List<ClientHttpRequestInterceptor> getInterceptors() {
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put(HttpHeaders.ACCEPT, "*");
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE);
HeaderHttpRequestInterceptor headerHttpRequestInterceptor = new HeaderHttpRequestInterceptor();
headerHttpRequestInterceptor.setRequestHeaders(requestHeaders);
headerHttpRequestInterceptor.setResponseHeaders(responseHeaders);
BasicAuthenticationRequestInterceptor basicAuthenticationRequestInterceptor =
new BasicAuthenticationRequestInterceptor(username, password);
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(basicAuthenticationRequestInterceptor);
interceptors.add(headerHttpRequestInterceptor);
return interceptors;
}
private List<HttpMessageConverter<?>> getMessageConverters() {
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
supportedMediaTypes.add(MediaType.APPLICATION_XML);
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =
new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
messageConverters.add(mappingJackson2HttpMessageConverter);
return messageConverters;
}
private HttpComponentsClientHttpRequestFactory getHttpComponentsClientHttpRequestFactory()
throws NoSuchAlgorithmException {
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setConnectTimeout(connectTimeout);
requestConfigBuilder.setSocketTimeout(socketTimeout);
RequestConfig requestConfig = requestConfigBuilder.build();
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultRequestConfig(requestConfig);
httpClientBuilder.setMaxConnPerRoute(maxConnPerRoute);
httpClientBuilder.setMaxConnTotal(maxConnTotal);
httpClientBuilder.setSSLSocketFactory(new CustomSslConnectionSocketFactory());
return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}