Volley is a powerful HTTP library for android. Most HTTP requests have ready-to-use implementation. However, you can also make custom requests to make best use of this powerful volley library. In this post, i will show you how to download a file directly to SDCard using inputstream and volley library. Also, as a general standard of downloading a file we get file name and file type in the response headers. By default Response.success() method of volley only pass Response.data and not Response.headers. So many developers find it difficult to access response headers while using Volley. In this post, we will see how we can access these headers and inputstream to create a file on SDCard.

First, we need create a custom class which extends the Volley Request class. To download the file data we can create a custom byte array request. This byte array can be converted into inputstream that will write data to the SDCard. Following InputStreamVolleyRequest.java file shows how to create a custom byte array request and access response headers that will be later used to create the file name.
InputStreamVolleyRequest.java

Now in our main activity i.e., FileDownloadActivity.java, we will use the above class in following manner to make the request for download:

Note, the request variable here is made global, so that we can use this variable to access the response header in onResponse() method. Next we need to convert the response received into input stream and then create file in SDCard and write data into it. We do that in following onResponse() method:

This is all you need to do to use volley for downloading a file directly to SDCard. But, what i would like to mention is that Volley is not suitable for large download or streaming operations, since Volley holds all responses in memory during parsing. For large download operations, consider using an alternative like DownloadManager.

To have a look at the whole project, please visit GitHub Beyondroid Volley File Download.