Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading