由于ECONNRESET(对等方重置连接),大多数情况下,使用Retrofit2上载二进制文件通常失败,

问题描述 投票:0回答:2

我正在使用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");
        }
    });

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

发送失败: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方法,它总是可以正常工作而没有任何错误!

java android upload retrofit2 okhttp3
2个回答
1
投票

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

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

此错误是由于文件大而互联网速度低,所以连接超时。


0
投票

我知道得有点晚,但是这一行代码解决了我的问题,请在调用方法之前编写它。我希望它对其他人有用。

    System.setProperty("http.keepAlive", "false");
© www.soinside.com 2019 - 2024. All rights reserved.