我有一个使用 Retrofit 1.9 和 Spring Server 的 Android 应用程序。 Android应用程序可以完美下载文件。我正在尝试迁移到 Retrofit 2.0。
改造1.9代码
Controller 服务器:
@RequestMapping(value = GET_MAP , method = RequestMethod.GET)
public void getMap(@PathVariable("filename")String filename
,HttpServletResponse response) throws IOException {
Files.copy(filename + ".zip", response.getOutputStream());
}
Android 接口(interface) API
@Streaming
@GET(GET_MAP)
public Response getMap(@Path("filename") long id);
<小时/>
因此,在谷歌搜索迁移后,为了下载 Retrofit 2.0
中的文件我必须使用Call<ResponseBody>
在我的 Android 接口(interface) API 中。我尝试过这样的事情:
选项 1 Controller 服务器代码
@RequestMapping(value = GET_MAP , method = RequestMethod.GET)
public void getMap(@PathVariable("filename")String filename
,HttpServletResponse response) throws IOException {
Files.copy(filename + ".zip", response.getOutputStream());
}
选项 2 Controller 服务器代码
@RequestMapping(value = GET_MAP , method = RequestMethod.GET)
public @ResponseBody HttpServletResponse getMap(@PathVariable("filename")String filename
,HttpServletResponse response) throws IOException {
Files.copy(filename + ".zip", response.getOutputStream());
return response;
}
Android 接口(interface) API
@Streaming
@GET(GET_MAP)
public Call<ResponseBody> getMap(@Path("filename") long id);
但是使用这两个选项,响应长度给我-1:
response.body().contentLength() = -1
我如何迁移 Controller 方法?
最佳答案
在服务器上尝试了几种响应配置后,这对我有用:
获取文件作为
新文件
使用
org.springframework.core.io.FileSystemResource.FileSystemResource
库将文件作为 ResponseBody 传递。@RequestMapping(value = GET_MAP , method = RequestMethod.GET) public @ResponseBody Resource getMap(@PathVariable("filename")String filename ,HttpServletResponse response) throws IOException { File file = new File(filename + ".zip"); return new FileSystemResource(file); }
关于java - 使用 Retrofit 2.0 和 Spring Server 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049827/