Retrofit - File uploading is successful but onFailure callback is executed

23 views Asked by At

I am working on an Android application in which I would like to upload an image file using retrofit and update the local DB with upload status from onResponse callback.

It works fine when there is no issue with internet.

But, If internet connection is interupted when retrofit already started to uploaded the file, it goes to onFailure callback with the error Error: java.net.SocketException: Connection reset.

Due to this, the local DB's status is still not updated. But, If I look into the server's DB, the file is uploaded. When our Android device is recovered from connectivity issue, it thinks that the file is still not uploaded(because local DB is not updated) and retries the upload.

Please help me to understand on how to handle this case.

Below is the code snippet

 File file = new File(path);
 OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
 MultipartBody.Part body = MultipartBody.Part.createFormData("FileInfo", file.getName(), 
 requestFile);
 Gson gson = new GsonBuilder().setLenient().create();
 Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(baseURL)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client)
                        .build();

 ApiConfigInterface api = retrofit.create(ApiConfigInterface.class);
 Call call = api.uploadImage(body,
                        apiEndPoint,
                        RequestBody.create(MediaType.parse("multipart/form-data"), formData1),
                        RequestBody.create(MediaType.parse("multipart/form-data"), formData2))
                        );

 call.enqueue(new Callback() {
                    @Override
                    public void onResponse(Call call, retrofit2.Response response) {
                      // Updating the local DB
                     }

                       @Override
                    public void onFailure(Call call, Throwable throwable) {
                      // Showing error message to the user
                     }
                       
0

There are 0 answers