Retrofit 使用心得 -使用Retrofit2框架下载大文件


请求方式如下:需要加入 @Streaming,这个返回的是一个流。

/**
 * 作用:访问网络,下载大文件。
 * 默认情况下,Retrofit在处理结果前会将服务器端的Response全部读进内存。
 * 如果服务器端返回的是一个非常大的文件,则容易oom。
 *
 * @return
 */
@Streaming
@GET
Call<ResponseBody> getNetworkDataAsync(@Url String urlString);

下载大文件代码:

//使用Retrofit2框架下载大文件
new Thread(new Runnable() {
    @Override
    public void run() {
        String urlString = Constant.URL_DOWNLOAD_VIDEO;
        call_big = serverInterface.getNetworkDataAsync(urlString);

        try {
            Response<ResponseBody> response = call_big.execute();
            InputStream is = response.body().byteStream();
            String filename = urlString.substring(urlString.lastIndexOf("/") + 1);
            Boolean flag = SDCardHelper.saveFileToSDCardPrivateCacheDir(is,
                    filename, mContext);

            if (flag) {
                Intent intent = new Intent();
                intent.setAction("com.steven.android_retrofit2qiushi");
                Bundle bundle = new Bundle();
                String filePath = SDCardHelper.getSDCardPrivateCacheDir(mContext)
                        + File.separator + filename;

                bundle.putString("path", filePath);
                intent.putExtras(bundle);
                sendBroadcast(intent);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

所使用的方法:

getNetworkDataAsync

saveFileToSDCardPrivateCacheDir()这方法一遍下载一边写入内存卡,有效的减少了oom

// 往SD卡的私有Cache目录下保存文件public static boolean saveFileToSDCardPrivateCacheDir(InputStream data, String fileName, Context context) {   BufferedInputStream bis = null;   BufferedOutputStream bos = null;   if (isSDCardMounted()) {      File file = context.getExternalCacheDir();      try {         bis = new BufferedInputStream(data);         bos = new BufferedOutputStream(new FileOutputStream(new File(               file, fileName)));         byte[] buffer = new byte[1024*8];         int c=0;         while((c=bis.read(buffer))!=-1) {            bos.write(buffer, 0 ,c);            bos.flush();         }         return true;      } catch (Exception e) {         e.printStackTrace();      } finally {         try {            if (bis != null) {               bis.close();            }            if (bos != null) {               bos.close();            }         } catch (IOException e) {            e.printStackTrace();         }      }   }   return false;}

// 获取SD卡私有Cache目录的路径
public static String getSDCardPrivateCacheDir(Context context) {
   return context.getExternalCacheDir().getAbsolutePath();
}
下载完成后,发送广播。进行相应的操作。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
retrofit-spring-boot-starter是一个用于整合Retrofit库和Spring Boot的starter项目,它可以简化在Spring Boot中使用Retrofit的配置和使用。 以下是retrofit-spring-boot-starter的使用方法: 1. 在你的Spring Boot项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.github.lianjiatech</groupId> <artifactId>retrofit-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> ``` 2. 创建一个接口,用于定义Retrofit的API接口。例如: ```java import retrofit2.http.GET; import retrofit2.http.Path; public interface MyApi { @GET("/users/{username}") User getUser(@Path("username") String username); } ``` 3. 在你的Spring Boot应用程序中,使用`@Autowired`注解将Retrofit的API接口注入到你的代码中。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import retrofit2.Retrofit; @Service public class MyService { private final MyApi myApi; @Autowired public MyService(Retrofit retrofit) { this.myApi = retrofit.create(MyApi.class); } public User getUser(String username) { return myApi.getUser(username); } } ``` 4. 现在你可以在你的代码中使用`MyService`来调用Retrofit的API接口了。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { private final MyService myService; @Autowired public MyController(MyService myService) { this.myService = myService; } @GetMapping("/users/{username}") public User getUser(@PathVariable String username) { return myService.getUser(username); } } ``` 以上是retrofit-spring-boot-starter的基本用法。你可以根据自己的需求进行配置和使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值