Showing posts with label Okhttp. Show all posts

Download file using Okio in Android


Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java. 

In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp

Coding Part

Create a new project in Android Studio.

Add following dependencies to your app-level build.gradle file.
compile 'com.squareup.okhttp3:okhttp:3.6.0'
Don't forget to add the following permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Implementation

Paste the following code in your Activity and Here, I have kept as MainActivity.java
public void downloadImg(View view) {
 try {
  Request request = new Request.Builder()
    .url(imageLink)
    .build();
  new OkHttpClient().newCall(request).enqueue(new Callback() {
   @Override
   public void onFailure(Call call, IOException e) {
   }

   @Override
   public void onResponse(Call call, Response response) 
    throws IOException {
    if (!folder.exists()) {
     boolean folderCreated = folder.mkdir();
     Log.v("folderCreated", folderCreated + "");
    }
    file = new File(folder.getPath() + "/savedImg.png");
    if (file.exists()) {
     boolean fileDeleted = file.delete();
     Log.v("fileDeleted", fileDeleted + "");
    }
    boolean fileCreated = file.createNewFile();
    Log.v("fileCreated", fileCreated + "");
    BufferedSink sink = Okio.buffer(Okio.sink(file));
    sink.writeAll(response.body().source());
    sink.close();
    new DownloadImage(file).execute();
   }
  });
 } catch (Exception e) {
  e.printStackTrace();
 }
}
It is similar to Java I/O API. It has two important components as BufferSource and BufferSink.
  • BufferSource is like InputStream in Java I/O API and BufferSink is like OutputStream.
  • You can view any Source as an InputStream, and you can view any InputStream as a Source. Similarly for Sink and OutputStream. 

Demo


Download Code

You can download the full source code for this tutorial from the following Github link. If you Like this tutorial, Please star it in Github.

Download From Github