Retrofit 2.0 Multipart Request,以包括文件在内的表单数据发送布尔类型 [英] Retrofit 2.0 Multipart Request, send boolean type in form data including file

查看:431
本文介绍了Retrofit 2.0 Multipart Request,以包括文件在内的表单数据发送布尔类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用翻新版2.0上传文件.除了文件,我还有其他一些要与表单数据一起发送的参数,这些数据也包括布尔类型.我的请求声明是-

I am trying to upload a file using retrofit 2.0. Apart from file, I have few other params to be send with form data which include a boolean type also. My request declaration is -

@Multipart
    @POST("/upload/abc")
    Call<UploadResponse> uploadToServer(@Part("img_file\";filename=\"image") RequestBody file,
                                             @Part("access_token") RequestBody sessionKey,
                                             @Part("is_final") Boolean isFinal,
                                             @Part("sequence_id") Integer sequenceId,
                                             @Part("entity_id") RequestBody entityId,
                                             @Part("image_type") RequestBody imageType);

我正在使用GsonConverterFactory.我尝试了2种方法-

I am using GsonConverterFactory. I tried 2 approaches -

(1)我使用@Part("is_final") RequestBody isFinal而不是@Part("is_final") Boolean isFinal并将其与RequestBody.create(MediaType.parse("text/plain"), String.valueOf(true))一起发送

(1) Instead of @Part("is_final") Boolean isFinal I used @Part("is_final") RequestBody isFinal and sending it with RequestBody.create(MediaType.parse("text/plain"), String.valueOf(true))

(2)使用@Part("is_final") Boolean isFinal并使用Boolean.true发送.

(2) Using @Part("is_final") Boolean isFinal and sending with Boolean.true.

在两种情况下,在服务器端接收到的"is_final"都是Unicode或作为字符串而不是布尔值.

In both the cases, "is_final" received on server side is Unicode or as a String instead of boolean value.

实现此目标的最佳方法是什么

What is the best way to achieve this

推荐答案

我通过-

compile 'com.squareup.retrofit2:converter-scalars:2.1.0'添加到gradle文件中.

Add compile 'com.squareup.retrofit2:converter-scalars:2.1.0' to the gradle file.

在创建改造实例时,添加

While creating retrofit instance, add

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("url")
                .client(builder.build())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

现在,您可以安全地随请求发送基本类型.

Now you can safely send primitive types with the request.

示例请求

Call<UploadResponse> uploadFile(@Part("img\"; filename=\"image") RequestBody file, 
                                @Part("session_key") String sessionKey, 
                                @Part("is_final") Boolean isFinal);

使用-

RequestBody fBody = RequestBody.create(null, someFile);
service.uploadFile(fBody, "some_string_session", true);

这篇关于Retrofit 2.0 Multipart Request,以包括文件在内的表单数据发送布尔类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆