0

I'm using retrofit2 for uploading binary image file:

File file = new File(filePath);
    RequestBody requestBody = new ProgressRequestBody(
            MediaType.parse("application/octet-stream"),
            file,
            this);

    Call<ResponseBody> call = service.uploadFile(requestBody);

    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,
                               Response<ResponseBody> response) {

            if (!response.isSuccessful()) {
                Toasti.showS("fail");
                return;
            }

            Log.v("Upload", "success");
            UploadFileOutput uploadFileOutput = new UploadFileOutput();
            try {
                uploadFileOutput =
                        new Gson().fromJson(response.body().string(), UploadFileOutput.class);
            } catch (IOException e) {
                e.printStackTrace();
            }


  ImageLoader.getInstance().displayImage(uploadFileOutput.imageSrc, giftImageview);
            }

        }

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

But most of the times(sometimes it works fine!) it fails because of this error:

sendto failed: ECONNRESET (Connection reset by peer)

I read lots of post and tutorials:

java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)

Getting “SocketException : Connection reset by peer” in Android

retrofit.RetrofitError: sendto failed: ECONNRESET (Connection reset by peer)

But none of them helped me.

I test api method with postman, It always works without any error!

Hamed Ghadirian
  • 6,159
  • 7
  • 48
  • 67

1 Answers1

1

After days of testing and searching I found that I should increase timeout of okhttp client by readTimeout and readTimeout:

longTimeOutHttpClient = new OkHttpClient.Builder()
            .readTimeout(120, TimeUnit.SECONDS)
            .connectTimeout(120, TimeUnit.SECONDS)
            .build();
    longTimeoutRetrofitBuilder = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClient);
    longTimeOutRetrofit = longTimeoutRetrofitBuilder.baseUrl(URIs.BASE_URL + 
    URIs.API_VERSION).build();

    longTimeoutService = longTimeOutRetrofit.create(RestAPI.class);

This error occurs because of big file size and low internet speed, so the connection time outs.

Hamed Ghadirian
  • 6,159
  • 7
  • 48
  • 67
  • 1
    I tried this with no luck in my case, it behaves exactly the same and throws the same error, sometimes working correctly, sometimes throwing the error. – Robert Ruxandrescu Jul 26 '22 at 13:19