Android :Retrofit实现文件的上传和下载

Retrofit实现文件的上传和下载

UploadService接口

package com.enjoy.networkdemo;

import java.io.File;

import io.reactivex.rxjava3.core.Flowable;
import okhttp3.MultipartBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Streaming;
import retrofit2.http.Url;

public interface UploadService {

    @POST("post")
    @Multipart
    Call<ResponseBody> upload(@Part MultipartBody.Part file);


    @Streaming
    @GET
    Call<ResponseBody> download(@Url String url);

    @Streaming
    @GET
    Flowable<ResponseBody> downloadRxJava(@Url String url);
}

UploadFileUnitTest实现普通方法和rxjava两种下载文件的办法

package com.enjoy.networkdemo.retrofit;

import com.enjoy.networkdemo.HttpbinService;
import com.enjoy.networkdemo.UploadService;

import org.junit.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class UploadFileUnitTest {
    Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
    UploadService uploadService = retrofit.create(UploadService.class);
//文件上传
    @Test
    public void uploadFileTest() throws IOException {
        File file1 = new File("C:\\Users\\Administrator\\Desktop\\1.txt");
        MultipartBody.Part part = MultipartBody.Part.createFormData("file1",
                "1.txt", RequestBody.create(file1, MediaType.parse("text/plain")));

        Call<ResponseBody> call =
                uploadService.upload(part);
        System.out.println(call.execute().body().string());
    }
//文件普通下载
    @Test
    public void downloadTest() throws IOException {
        Response<ResponseBody> response = uploadService.download(
            "https://fga1.market.xiaomi" +
                ".com/download/AppStore/07adf043b0b2c40371abc6c685363e83d27f3efd7/com.sdu.didi" +
                ".psnger.apk")
            .execute();
//        response.isSuccessful()
        InputStream inputStream = response.body().byteStream();
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\a.apk");
        int len;
        byte[] buffer = new byte[4096];

        while ((len = inputStream.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        inputStream.close();
    }
//文件rxjava实现下载
    @Test
    public void downloadRxjavaTest() {
        uploadService.downloadRxJava("https://fga1.market.xiaomi.com/download/AppStore/07adf043b0b2c40371abc6c685363e83d27f3efd7/com.sdu.didi.psnger.apk")
                .map(new Function<ResponseBody, File>() {
                    @Override
                    public File apply(ResponseBody responseBody) throws Throwable {
                        InputStream inputStream = responseBody.byteStream();
                        File file = new File("C:\\Users\\Administrator\\Desktop\\a.apk");
                        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 {

            }
        });
        while (true) {
        }
    }
}

参考

1、Android网络开源库-Retrofit(二) 文件上传、下载及进度监听

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中使用 Retrofit 上传图片可以通过 `@Multipart` 和 `@Part` 注解实现。以下是 Retrofit 2.0 实现图文上传的方法总结: 1. 添加依赖库 在项目的 `build.gradle` 文件中添加以下依赖库: ```groovy implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.retrofit2:converter-scalars:2.9.0' ``` 2. 创建 Retrofit 实例 ```java Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); ``` 3. 创建 API 接口 ```java public interface ApiService { @Multipart @POST("upload") Call<ResponseBody> upload( @Part("description") RequestBody description, @Part MultipartBody.Part file); } ``` 其中,`@Multipart` 注解表示这是一个包含文本和文件的表单;`@POST("upload")` 表示上传的 URL 地址;`@Part("description") RequestBody description` 表示上传的文本参数,`description` 是参数名,可以自己定义;`@Part MultipartBody.Part file` 表示上传文件参数。 4. 创建请求参数 ```java File file = new File(filePath); RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile); RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), "description"); ``` 5. 发送网络请求 ```java ApiService apiService = retrofit.create(ApiService.class); Call<ResponseBody> call = apiService.upload(description, body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { // 成功上传后的处理 } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { // 上传失败后的处理 } }); ``` 以上就是 Retrofit 2.0 实现图文上传的方法总结。注意,在 `AndroidManifest.xml` 文件中需要添加网络权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值