Retrofit 2 Multipart POST request sends extra quot

2019-03-19 03:12发布

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

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-19 03:17

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)
查看更多
Summer. ? 凉城
3楼-- · 2019-03-19 03:24

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!

查看更多
男人必须洒脱
4楼-- · 2019-03-19 03:30

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);
查看更多
登录 后发表回答