我正在使用retrofit2上传二进制图像文件:

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");
        }
    });


但大多数情况下(有时工作正常!)由于此错误而失败:


  sendto失败:ECONNRESET(对等方重置连接)


我读了很多文章和教程:

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)

但是他们都没有帮助我。

我用邮递员测试api方法,它总是可以正常工作!

最佳答案

经过数天的测试和搜索,我发现我应该通过readTimeoutreadTimeout增加okhttp客户端的超时时间:

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);


发生此错误的原因是文件较大且Internet速度较低,因此连接超时。

08-04 00:00