【问题标题】:Download File using Retrofit 2.0 and Spring Server使用 Retrofit 2.0 和 Spring Server 下载文件
【发布时间】:2017-02-24 06:42:06
【问题描述】:

我有一个使用 Retrofit 1.9 和 Spring Server 的 Android 应用程序。 Android应用程序可以完美下载文件。我正在尝试迁移到Retrofit 2.0

改造 1.9 代码

控制器服务器:

@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 接口 API

@Streaming
@GET(GET_MAP)
public Response getMap(@Path("filename") long id);

因此,在谷歌搜索迁移以下载 Retrofit 2.0 中的文件之后,我必须在我的 Android 接口 Api 中使用 Call<ResponseBody>。我尝试过这样的事情:

选项 1 控制器服务器代码

@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 控制器服务器代码

@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 接口 API

@Streaming
@GET(GET_MAP)
public Call<ResponseBody> getMap(@Path("filename") long id);

但是使用这两个选项,响应长度给了我-1:

response.body().contentLength() = -1

我必须如何迁移 Controller 方法?

【问题讨论】:

    标签: java android spring retrofit2 downloadfile


    【解决方案1】:

    在服务器上尝试了几种响应配置后,这对我有用:

    1 - 获取文件为new File

    2 - 使用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);
        }
    

    【讨论】:

      猜你喜欢
      • 2015-09-16
      • 2022-01-10
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多