Android with Retrofit2 OkHttp3 - Multipart POST Error

后端 未结 1 1645
南旧
南旧 2021-01-06 03:09

I am using Retrofit2 with OkHttp on Android for HTTP request. Here I am doing a POST request with document upload. I ran into error below:

D/OkHttp: <-- 5         


        
相关标签:
1条回答
  • 2021-01-06 03:55

    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

    0 讨论(0)
提交回复
热议问题