如何用OkHttp下载多个文件?

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

我知道如何用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 } } }); 

我怎样才能下载所有的文件,而不只是一个?

我将在这里举一个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 } 

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

我假设你有一个URL列表下载文件。

 String[] urls = //; 

为每个网址发出请求。

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