我有以下Rest資源從DB下載文件。它在瀏覽器中工作正常,但是,當我嘗試從Java客戶端執行操作時,我得到了406(不接受錯誤)。如何以編程方式使用Spring使用Rest API中的文件?
...
@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);
}
...
客戶端部署有不同的端口在同一臺服務器(信息提供了正確的名稱):
...
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());
...
缺少什麼我在這裏?
這些文件可能很大嗎?我建議將它流式傳輸,而不是將所有字節加載到數組中,然後將其發送回 – 2014-10-28 16:21:25
@TritonMan文件的大小約爲90Kb,所以不會太大。 – Sami 2014-10-28 16:28:32
不知道這是否有幫助,但我的團隊剛開始使用改造我們的休息電話。基本上你定義了一個帶註釋的接口,然後你可以像其他方法一樣調用其他的方法。 Retrofit處理後臺中的所有細節: http://square.github.io/retrofit/ – StormeHawke 2014-10-31 12:24:09