Retrofit 2 Multipart POST request sends extra quotes to PHP

烈酒焚心 提交于 2019-12-03 06:00:18

For your issue, please use as the documentation

Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

So, add compile 'com.squareup.retrofit2:converter-scalars:2.0.1' into build.gradle file

Then...

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_URL_BASE)
    .addConverterFactory(ScalarsConverterFactory.create())
    //.addConverterFactory(GsonConverterFactory.create())
    .build();

Hope it helps!

Pranav Mittal

Use RequestBody for all your parameters. Please go through below code!!

File file = new File(imagePath);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part imageFileBody = MultipartBody.Part.createFormData("media", file.getName(), requestBody);
RequestBody id = RequestBody.create(MediaType.parse("text/plain"),addOfferRequest.getCar_id());
ApiCallback.MyCall<BaseResponse> myCall = apiRequest.editOfferImage(imageFileBody,id);

Use RequestBody class of Retrofit instead of String

@Multipart
@POST(ApiURL)
ApiCallback.MyCall<BaseResponse> editOfferImage(@Part MultipartBody.Part imageFile,@Part("id") RequestBody id);

If you would rather not use a converter, here's what I did to send a multipart request containing an image file, and 2 strings:

@Multipart
@POST("$ID_CHECK_URL/document")
fun postMultipart(@Part imageFile: MultipartBody.Part, @Part string2:  MultipartBody.Part, @Part string2:  MultipartBody.Part)

And calling it this way:

    val body = RequestBody.create(MediaType.parse("image/jpg"), file)
    val imageFilePart = MultipartBody.Part.createFormData("file", file.name, reqFile)

    val string1Part = MultipartBody.Part.createFormData("something", "string 1")

    val string2Part = MultipartBody.Part.createFormData("somethingelse", "string 2")

    service.postDocument(imageFilePart, string1Part, string2Part)

I faced this on my project today and this is how I solved it. I changed @Part on my string and other primitive values to @Query, and for file (in my case image) i used @Part. Looks like @Query treats strings in a different way compared to @Part.

So my answer to original question would look like this:

@Multipart
@POST("api.php")
Call<ResponseBody> doAPI(
  @Query("lang") String lang,
  @Part("file\"; filename=\"image.jpg") RequestBody file
);

This should send string values without unwanted quotes. Sadly, I cant explain why this works, it has something to do with @Part encoding of data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!