使用Retrofit实现文件的上传和下载

一、前言

使用Retrofit实现文件的上传和下载,代码是正确的代码但是我也不知道为什么运行不出来。

报错内容可以给你们看一下暂时没有解决。

1.文件的上传报错内容

什么添加读写权限,降低目标sdk的版本都试过了不行。有木有会的留个言。

2.文件的下载报错内容

二、代码实现文件上传

1.创建接口类对象

public interface UpLoadService {
    /**
     * 文件上传
     * 切记导包不要导错
     * @param file
     * @return
     */
    @POST("post")
    @Multipart
    Call<ResponseBody> upLoad(@Part MultipartBody.Part file);

}

2,代码实现

public class UpLoadFileUnitTest {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();//创建retrofit对象
    UpLoadService upLoadService = retrofit.create(UpLoadService.class);

    @Test
    public void upLoadFileTest() throws IOException {
        File file1 = new File("C:\\Users\\Anglin\\Desktop\\1.doc");
        MultipartBody.Part part = MultipartBody.Part.createFormData("file1", "1.doc",
                RequestBody.create(file1, MediaType.parse("text/plain")));
        Call<ResponseBody> call = upLoadService.upLoad(part);
        System.out.println(call.execute().body().string());
    }
}

三、实现文件下载

1.创建接口类对象

public interface UpLoadService {


    /**
     * 下载文件
     * @param url
     * @return
     */
    @Streaming
    @GET
    Call<ResponseBody> downLoad(@Url String url);


}

2.代码实现

public class UpLoadFileUnitTest {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();//创建retrofit对象
    UpLoadService upLoadService = retrofit.create(UpLoadService.class);


    @Test
    public void downLoadTest() throws IOException {
        Response<ResponseBody> response = upLoadService.downLoad("https://repo.maven.apache.org/maven2/org/bouncycastle/bcprov-jdk16/1.46/bcprov-jdk16-1.46.jar")
                .execute();
        InputStream inputStream = response.body().byteStream();
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Anglin\\Desktop\\a.jar");
        int len;
        byte[] buffer = new byte[4096];
        while ((len = inputStream.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
    }


}

四、使用Rxjava实现文件下载

1.创建接口类对象

public interface UpLoadService {

    /**
     * 使用rxJava下载文件
     */
    @Streaming
    @GET
    Flowable<ResponseBody> downLoadRxJava(@Url String url);
}

2.代码实现

public class UpLoadFileUnitTest {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();//创建retrofit对象
    UpLoadService upLoadService = retrofit.create(UpLoadService.class);


    @Test
    public void downLoadRxJavaText(){
        upLoadService.downLoadRxJava("https://repo.maven.apache.org/maven2/org/bouncycastle/bcprov-jdk16/1.46/bcprov-jdk16-1.46.jar")
                .map(new Function<ResponseBody, File>() {
                    @Override
                    public File apply(ResponseBody responseBody) throws Throwable {
                        InputStream inputStream = responseBody.byteStream();
                        File file = new File("C:\\Users\\Anglin\\Desktop\\a.jar");
                        FileOutputStream fos = new FileOutputStream(file);
                        int len;
                        byte[] buffer = new byte[4096];
                        while ((len = inputStream.read(buffer)) != -1){
                            fos.write(buffer,0,len);
                        }
                        fos.close();
                        inputStream.close();
                        return file;
                    }
                }).subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Throwable {

                    }
                });
    }
}

五、总结

在实现文件的下载时需要在接口类对象中添加@Streaming,从而防止内存泄漏。

 

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Retrofit2是一个流行的Android网络框架,可以通过注解和动态代理来简化网络请求的步骤。在使用Retrofit2进行文件上传时,可以使用@Multipart注解和@PartMap注解来实现文件上传。\[1\] 具体的实现步骤如下: 1. 在Retrofit接口中使用@Multipart注解标记该方法为多部分请求。 2. 使用@POST注解指定上传文件的URL。 3. 使用@PartMap注解将文件参数以Map的形式传递给方法。 4. 在Map中,键是参数的名称,值是RequestBody类型的文件内容。 例如,可以使用以下代码来实现文件上传: ``` @Multipart @POST("upload") Observable<String> uploadFiles(@PartMap Map<String, RequestBody> files); ``` 其中,files是一个Map,键是文件参数的名称,值是RequestBody类型的文件内容。 Retrofit2之所以被广泛使用,是因为它能够根据注解封装网络请求,并通过转化器将原始的HTTP响应内容转化为我们需要的对象。这使得使用Retrofit2非常方便。\[2\]\[3\] #### 引用[.reference_title] - *1* *3* [Retrofit2 multpart多文件上传详解](https://blog.csdn.net/jdsjlzx/article/details/51649382)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [retrofit2上传文件总结](https://blog.csdn.net/u011323666/article/details/52288753)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值