使用Retrofit上传文件

本文介绍如何使用Retrofit和Multipart进行文件上传操作。通过示例代码详细展示了配置依赖、定义请求接口、构造请求参数及异步调用等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Retrofit和RxJava系列博客:
使用Retrofit上传文件
使用Gson解析Retrofit返回结果
Retrofit和RxJava结合使用
使用Retrofit和RxJava进行轮询操作


Retrofit是Square公司开发的网络请求框架,其底层封装了okhttp进行实际的网络请求操作。关于其基础用法,强烈推荐腾讯bugly社区的博文《深入浅出 Retrofit》:

http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=1117

本文将以使用Multipart方式上传图片为例,总结一下Retrofit的使用方法。

添加依赖

在build.gradle中加入依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'

定义Multipart请求接口

Multipart在http中常常用于上传文件。首先需要使用注解@Multipart,表明该接口使用Multipart方式进行请求。在接口的upload方法中,使用@Part注解定义上传的内容,这里的第一个@Part表示一个键为UserId、值为description的参数;第二个@Part表示该参数为一个MultipartBody.Part类型的文件file

public interface FileUploadService {
        @Multipart
        @POST("EntranceGuardes/app/appOpen_pushdDataToApp.action")
        Call<ResponseBody> upload(@Part("userId") RequestBody description,
                                  @Part MultipartBody.Part file);
    }

传入文件

首先,需要构造一个FileUploadService对象service

Retrofit retrofit = new Retrofit.Builder().baseUrl("http://172.18.81.155:8080/").build();

FileUploadService service = retrofit.create(FileUploadService.class);

接下来需要调用serviceupload方法。upload方法的第一个参数是@Part("userId") RequestBody description,使用RequestBody.create方法就可以将字符串s变为RequestBody类型。值得注意的是MediaType.parse("text/plain")中使用MIME来说明上传数据的类型。

String s = "1006";

RequestBody description = RequestBody.create(MediaType.parse("text/plain"), s);

如果加入要上传的图片呢?首先需要打开图片文件,随后使用RequestBody.create创建一个RequestBody对象,然后调用MultipartBody.Part.createFormDataRequestBody对象转变为MultipartBody.Part对象。注意到这里的MIME指定为image/*,表明这部分数据是图片类型的文件。

File file = new File("/storage/sdcard/Desert.jpg");
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

异步调用

定义完成请求以后就需要调用了,retrofit和okhttp一样提供了同步调用和异步调用两种方式,常用的就是异步调用方式。异步调用只需要在enqueue方法中传入回调对象就可以了。在回调的接口中,需要实现两个方法onResponseonFailure,分别对应中请求成功响应和请求失败两种情况。

    Call<ResponseBody> call = service.upload(description, body);

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                Log.d("main", response.body().string());
                Log.d("main",Thread.currentThread().getName());                         
                } catch (IOException e) {
                    e.printStackTrace();
                    }
                }
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
                    }
                });

完整代码

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

                File file = new File("/storage/sdcard/Desert.jpg");

                Retrofit retrofit = new Retrofit.Builder().baseUrl("http://172.18.81.155:8080/").build();

                FileUploadService service = retrofit.create(FileUploadService.class);

                RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

                String s = "1006";
                RequestBody description = RequestBody.create(MediaType.parse("text/plain"), s);

                Call<ResponseBody> call = service.upload(description, body);

                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            Log.d("main", response.body().string());
                            Log.d("main",Thread.currentThread().getName());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
    }

    public interface FileUploadService {
        @Multipart
        @POST("EntranceGuardes/app/appOpen_pushdDataToApp.action")
        Call<ResponseBody> upload(@Part("userId") RequestBody description,
                                  @Part MultipartBody.Part file);

    }

}

代码地址

https://github.com/flyingzhao/JavaExperiment/tree/master/androidapp/RetrofitTest

### 使用 Retrofit 进行文件上传Retrofit 2 中,`TypedFile` 类已经被移除,取而代之的是利用 `OkHttp` 库中的类来处理文件上传操作[^1]。下面是一个具体的例子展示如何通过 Retrofit 实现文件上传功能。 #### 创建 API 接口定义 首先需要创建一个接口用于描述 HTTP 请求方法,在此案例中为 POST 方法并指定路径以及参数: ```java public interface FileUploadService { @Multipart @POST("/upload") Call<ResponseBody> uploadImage( @Part MultipartBody.Part file, @Part("description") RequestBody description); } ``` 这里使用了 `@Multipart` 注解表明这是一个多部分表单请求;`@Part MultipartBody.Part file` 表示要上传文件部分;`@Part("description") RequestBody description` 则是用来传递额外的信息比如图片说明等文字内容。 #### 准备待上传的数据 接着准备实际要发送给服务器的内容,包括文件本身和其他附加信息: ```java // Create a file object from your image path. File file = new File(imagePath); // Create RequestBody instance from file RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file); // Create MultipartBody.Part using file name as the key MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), requestBody); // Add another part within the multipart request containing a description string String descriptionString = "This is some text describing my awesome picture!"; RequestBody description = RequestBody.create( MediaType.parse("text/plain"), descriptionString); ``` 上述代码片段展示了如何构建包含图像数据及其描述文本的消息体。注意设置合适的 MIME 类型以便接收端能够正确解析接收到的数据流。 #### 初始化 Retrofit 并执行网络请求 最后一步就是初始化 Retrofit 客户端并将之前定义好的服务实例化出来调用对应的方法发起真正的 HTTP 请求: ```java Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://yourserveraddress.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); FileUploadService service = retrofit.create(FileUploadService.class); Call<ResponseBody> call = service.uploadImage(body, description); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Log.v("UPLOAD", "success"); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e("UPLOAD", "error:" + t.getMessage()); } }); ``` 这段代码实现了向指定地址发送带有附件(即图片)和描述字符串的 POST 请求,并监听响应结果来进行相应的日志记录或其他业务逻辑处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值