Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace deprecated okhttp.RequestBody.create()

I try to upload an image from an Android App to a Django server using Retrofit 2 and OkHttp3. For that, I used to create a RequestBody instance using the following lines:

RequestBody requestImageFile =
                    // NOW this call is DEPRECATED
                    RequestBody.create(
                            MediaType.parse("image/*"),

                            // a File instance created via the path string to the image
                            imageFile
                    );

I used the previous instance in the next method call as argument:

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part image = MultipartBody.Part.createFormData("image", imageFile.getName(), requestImageFile);

Finally, I fired up the Retrofit interface to do the rest:

// finally, execute the request
Call<ResponseBody> call = service.upload(image);
call.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.v("Upload", "success");
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("Upload error:", t.getMessage());
     }
});

Some months ago, Android Studio did not told me that create() was deprecated. When I open the project now, it tells me that create() is deprecated. Does somebody know how to fix it ?

like image 757
ebeninki Avatar asked Nov 01 '19 14:11

ebeninki


1 Answers

Just swap the parameters from

RequestBody.create(MediaType.parse("image/*"), imageFile);

to

RequestBody.create(imageFile, MediaType.parse("image/*"));
like image 167
Shashanth Avatar answered Oct 20 '22 18:10

Shashanth