Android with Retrofit2 OkHttp3 - Multipart POST Error

一曲冷凌霜 提交于 2019-11-30 21:53:58
Shuwn Yuan Tee

After referring to Retrofit 2 can't upload a file with two additional separate string parameters , I implemented according to @TommySM suggestion. I got my problem solved with this:

// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(
            mediaType,
            myFile);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part file = MultipartBody.Part.createFormData(
            "documentImage",
            myFile.getName(),
            requestFile);

// add another part within the multipart request
RequestBody token = RequestBody.create(
            MediaType.parse("text/plain"),   // Fixed here
            //okhttp3.MultipartBody.FORM,    => PROBLEMATIC
            userID);

RequestBody docType = RequestBody.create(
            MediaType.parse("text/plain"),   // Fixed here
            //okhttp3.MultipartBody.FORM,    => PROBLEMATIC
            docTypeStr);

// token, documentType, file
this.call = driveWealthApi.addDocument(token, docType, file);

Those String parameter should be specified as Content-Type: text/plain rather than Content-Type: multipart/form-data.

See screenshots for details:

1) Problematic POST

2) Correct POST

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