使用RestTemplate下载Localhost导致406

时间:2016-05-26 07:43:46

标签: java spring get resttemplate http-status-code-406

我正在测试restTemplate

从localhost下载文件

这是我的测试:

@Test
public void download_test() throws Exception {     

 List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(new ByteArrayHttpMessageConverter());

    RestTemplate restTemplate = new RestTemplate(messageConverters);

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
    HttpEntity<String> entity = new HttpEntity<String>(headers);

    String url = "http://localhost:8083/images/11.jpg";
    ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET,
            entity, byte[].class);

    if (response.getStatusCode() == HttpStatus.OK) {
        Files.write(Paths.get("downloadedImage.jpg"), response.getBody());
    }
}

在我的WebConfig我已配置MssageConvertersContentNegotiation,如下所示:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new ByteArrayHttpMessageConverter());
    super.configureMessageConverters(converters);
}

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false).
            favorParameter(true).
            parameterName("mediaType").
            ignoreAcceptHeader(false).
            useJaf(false).
            defaultContentType(MediaType.APPLICATION_JSON).
            mediaType("xml", MediaType.APPLICATION_XML).
            mediaType("json", MediaType.APPLICATION_JSON).
            mediaType("octet-stream", MediaType.APPLICATION_OCTET_STREAM);
}
...}

为什么我收到406错误?

我错过了什么吗?

org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable

0 个答案:

没有答案