Search code examples
phpandroidmultipartform-datamultipartretrofit2

Retrofit 2 Multipart POST request sends extra quotes to PHP


Using Retrofit 2.0.1, there is a call function in my API interface defined in Android App:

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

I send the request like this:

Call call = service.doAPI("eng", imageFile);

where imageFile is a RequestBody created with a File object. The upload image part has no problem, while the @Part("lang") String lang part got extra quotes in server.

In PHP side, it is written as follow:

$lang = trim($_POST['lang']);

which returns "eng". Why there is an extra double quote surrounded the string?

of course I can strip the trailing and leading double quotes, but it's weird to do so


Related Issue: https://github.com/square/retrofit/issues/1210


Solution

  • 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!