且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Spring 以编程方式使用来自 Rest API 的文件?

更新时间:2022-01-28 07:35:06

响应代码是 406 Not Accepted.您需要指定一个Accept"请求标头,该标头必须与 RequestMapping 的produces"字段匹配.

The response code is 406 Not Accepted. You need to specify an 'Accept' request header which must match the 'produces' field of your RequestMapping.

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());    
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<String>(headers);

ResponseEntity<byte[]> response = restTemplate.exchange(URI, HttpMethod.GET, entity, byte[].class, "1");

if(response.getStatusCode().equals(HttpStatus.OK))
        {       
                FileOutputStream output = new FileOutputStream(new File("filename.jar"));
                IOUtils.write(response.getBody(), output);

        }

一个小警告:不要对大文件这样做.RestTemplate.exchange(...) 总是将整个响应加载到内存中,因此您可能会遇到 OutOfMemory 异常.为了避免这种情况,不要使用 Spring RestTemplate,而是直接使用 Java 标准 HttpUrlConnection 或 apache http-components.

A small warning: don't do this for large files. RestTemplate.exchange(...) always loads the entire response into memory, so you could get OutOfMemory exceptions. To avoid this, do not use Spring RestTemplate, but rather use the Java standard HttpUrlConnection directly or apache http-components.