Download a File with OkHttp

OkHttp 用起來真的很方便。

官方網站:http://square.github.io/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();
        }
    });
}

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *