gpt4 book ai didi

java - 使用 Retrofit2 上传二进制文件大多数时候会因 ECONNRESET(连接被对等方重置)而失败

转载 作者:行者123 更新时间:2023-12-02 12:46:27 25 4
gpt4 key购买 nike

我使用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 failed: ECONNRESET (Connection reset by peer)

我阅读了很多帖子和教程:

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)

但他们都没有帮助我。

我用postman测试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);

出现此错误的原因是文件较大且网速较低,导致连接超时。

关于java - 使用 Retrofit2 上传二进制文件大多数时候会因 ECONNRESET(连接被对等方重置)而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44754259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com