1. 程式人生 > >Download a File with OkHttp

Download a File with OkHttp

OkHttp 用起來真的很方便。

Download a file with OkHttp synchronously

Here is the sample source code to download a file synchronously then write the file temporarily to disk.

public void downloadFileSync(String downloadUrl) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request
.Builder().url(downloadUrl).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException(“Failed to download file: “ + response); } FileOutputStream fos = new FileOutputStream(“d:/tmp.txt”); fos.write(response.body().bytes()); fos.close(); }

Download a file with OkHttp asynchronously

Here is the sample code to download a file asynchronously then write it to disk.

public void downloadFileAsync(final String downloadUrl) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(downloadUrl).build(); client.newCall(request).enqueue(new
Callback() { public void onFailure(Call call, IOException e) { e.printStackTrace(); } public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException(“Failed to download file: “ + response); } FileOutputStream fos = new FileOutputStream(“d:/tmp.txt”); fos.write(response.body().bytes()); fos.close(); } }); }