我需要使用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
}
}
});
如何下载所有文件,而不只是一个?
答案 0 :(得分:3)
我只是在这里抛出一个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
}
这不仅简洁,而且还能处理错误和错误。线程同步
答案 1 :(得分:0)
我假设您有一个包含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
}