Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

android - Retrofit 2.0 Multipart Request, send boolean type in form data including file

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);

I am using GsonConverterFactory. I tried 2 approaches -

(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) Using @Part("is_final") Boolean isFinal and sending with Boolean.true.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I made it work by -

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.

Example Request

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

Call this method using -

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...