Search code examples
androidokhttp

How to get server response from multipart form file upload using okhttp


I am uploading a file to my server, and expecting a JSON response. I am using okhttp on my android app, and uploading the file like this :

// create request body from file to upload
RequestBody fileBody = RequestBody.create(new File(multimediaFilePath), MediaType.parse(contentType));
MultipartBody multipartBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("multimediaFile", "profile.jpg", fileBody)
                        .addFormDataPart("multimediaFormat", fileExtension)
                        .build();

// create request object
Request requestObj = new Request.Builder()
                    .url(url)
                    .post(multipartBody)
                    .build();

// call okhttp client
OkHttpClient httpClient = new OkHttpClient();
Response responseObj = httpClient.newCall(requestObj).execute();

// get server response if successful call
if (responseObj.isSuccessful())
  response = responseObj.body().toString();

The problem is, that the response that I am getting is not the response sent by my server, but the okhttp client's string function okhttp3.internal.http.RealResponseBody@5ff7632

Can someone please help me figure this out?

P.S. The file is successfully uploaded. The problem is, I am unable to get the response that the server is sending back


Solution

  • You should use OkHttp's string() function, not Java's toString() function.

    response = responseObj.body().string();