Search code examples
androidretrofit2multipart

Body request with multipart


This is my retrofit2 interface

@Multipart
@PUT("webservice")
fun setProfile(
    @Part("city") city: RequestBody,
    @Part("name") name: RequestBody,
    @Part("sex") sex: RequestBody,
    @Part("birthday") birthday: RequestBody,
    @Part("about_me") aboutMe: RequestBody,
    @Part img: MultipartBody.Part
): Observable<BaseResponse>

That's how I create these RequestBodies:

RequestBody.create(MediaType.parse("text/plain"), body.city),
RequestBody.create(MediaType.parse("text/plain"), body.name),
RequestBody.create(MediaType.parse("text/plain"), body.sex),
RequestBody.create(MediaType.parse("text/plain"), body.birthday),
RequestBody.create(MediaType.parse("text/plain"), body.about_me),

My webservice gets data like this:

Accept: application/jsonContent-Type: multipart/form-data; boundary=

Content-Disposition: form-data; name="city"    
Tokyo

Content-Disposition: form-data; name="name"   
John Smith

Content-Disposition: form-data; name="sex" 
male

Content-Disposition: form-data; name="avatar"; filename="avatar.png"
Content-Type: image/png
(img data)

When I send my data like described above I get 422 error code with the next description

field city is required to fill out

So, as I understood the webservice is unable to find these fields. But when I send data without img, just like @Body it works well. Any ideas?


Solution

  • Finally I've solved this. I had a long time discussion with backend developer and we found an error. I had to use POST and put into params the next field:

    params.put("_method", "PUT")