我有以下Rest资源从DB下载文件.它可以在浏览器中正常工作,但是,当我尝试从Java客户端执行此操作时,我得到406(不接受错误).
...
@RequestMapping(value="/download/{name}", method=RequestMethod.GET,
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody HttpEntity<byte[]> downloadActivityJar(@PathVariable String name) throws IOException
{
logger.info("downloading : " + name + " ... ");
byte[] file = IOUtils.toByteArray(artifactRepository.downloadJar(name));
HttpHeaders header = new HttpHeaders();
header.set("Content-Disposition", "attachment; filename="+ name + ".jar");
header.setContentLength(file.length);
return new HttpEntity<byte[]>(file, header);
}
...
Run Code Online (Sandbox Code Playgroud)
客户端部署在具有不同端口的同一服务器上(消息提供正确的名称):
...
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/activities/download/" + message.getActivity().getName();
File jar = restTemplate.getForObject(url, File.class);
logger.info("File size: " + jar.length() + " Name: " + jar.getName());
...
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
Gee*_*nte 19
响应代码为406 Not Accepted.您需要指定一个'Accept'请求标头,该标头必须与RequestMapping的'produce'字段匹配.
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);
}
Run Code Online (Sandbox Code Playgroud)
一个小警告:不要对大文件执行此操作.RestTemplate.exchange(...)总是将整个响应加载到内存中,因此您可以获得OutOfMemory异常.为避免这种情况,请不要使用Spring RestTemplate,而是直接使用Java标准HttpUrlConnection或apache http-components.
| 归档时间: |
|
| 查看次数: |
29928 次 |
| 最近记录: |