使用Retrofit和OkHTTPClient下载文件因TimeOut而停止

时间:2017-02-27 10:17:57

标签: android retrofit retrofit2 okhttp

我正在使用Retrofit下载文件,但是在下载停止几秒钟后,通过提供此错误“改装让线程暂停超时:下载期间为110 ”或主要是“ JavaBinder:!!!失败的粘合剂交易!!!(包裹大小= 2840),“,如何解决这个问题?文件可以是任何大小5MB,10MB,下载时间可以是任何取决于互联网速度。在延迟的情况下,下载不应该停止。

代码:

public void run() {

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                      try {
                          Response originalResponse = chain.proceed(chain.request());
                          return originalResponse.newBuilder()
                                  .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                                  .build();
                      }
                      catch (Exception e) {
                             e.printStackTrace();
                          progressListener.onError(e.getCause()+": "+e.getMessage());

                      }
                      return chain.proceed(chain.request());
                    }
                });
        AppGlobal.Log("usm_fileUrl","baseUrl= "+BASE_URL+" ,fileName= "+fileName);
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                ;
        Retrofit retrofit = builder.client(httpClient.build()).build();
        RetrofitInterface downloadService = retrofit.create(RetrofitInterface.class);
        Call<ResponseBody> call = downloadService.downloadFileByUrl(fileName);
        this.notificationId = this.mNotification.createNotification(fileTitle,"Downloading...");
        call.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, final retrofit2.Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    Log.d(TAG, "Got the body for the file");

                    new AsyncTask<Void, Long, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            saveToDisk(response.body());
                            return null;
                        }
                    }.execute();

                } else {
                    Log.d(TAG, "Connection failed " + response.errorBody());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
                Log.e(TAG, t.getMessage());
            }
        });

}

0 个答案:

没有答案