Zookey
Zookey

Reputation: 2707

How to download multiple files with OkHttp?

I need to download multiple files with OkHttp libarary. And after all downloads are finished I need to inform user.

I know how to download one file with OkHttp. Here is code:

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
            }
          }
        });

How I can dowload all files, not just one?

Upvotes: 1

Views: 2635

Answers (2)

martyglaubitz
martyglaubitz

Reputation: 1002

I'll just throw an RxJava / Kotlin example in here...

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
   }

Not only is this concise but also does it handle errors & thread synchronization

Upvotes: 4

giannisf
giannisf

Reputation: 2599

I am assuming that you have a list with URLs to download the files.

String[] urls = //;

for every url make a request.

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

}

Upvotes: 0

Related Questions