4

我正在测试通过以下方式从 localhost 下载文件restTemplate

这是我的测试:

@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

4

0 回答 0