1

我需要使用 OkHttp 库下载多个文件。在所有下载完成后,我需要通知用户。

我知道如何使用 OkHttp 下载一个文件。这是代码:

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
                .url(url)
                .build();
okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                Log.d("TAG", "download file fail: " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                if (response.isSuccessful()) {
               //I have response data of downloaded file
            }
          }
        });

如何下载所有文件,而不仅仅是一个?

4

2 回答 2

4

我将在这里抛出一个 RxJava / Kotlin 示例......

Observable.from(urls)
   .subscribeOn(Schedulers.io())
   .map { url ->
       val request = Request.Builder().url(url).build()
       okHttpClient.newCall(request).execute()
   }
   .observeOn(AndroidSchedulers.mainThread())
   .subscribe { responses -> 
       // responses: List<Response> - do something with it
       // nothify User (we're on the UI thread here)
   }, { error ->
       // handle the error
   }

这不仅简洁,而且还处理错误和线程同步

于 2016-03-01T10:19:19.837 回答
0

我假设您有一个包含 URL 的列表来下载文件。

String[] urls = //;

为每个 url 发出请求。

for (String url : urls) {
    Request request = new Request.Builder()
                .url(url)
                .build();
Response response = okHttpClient.newCall(request);
// do something with the response

}
于 2016-02-29T18:20:17.257 回答