Friday, 30 June 2017

Android: Sending headers with HttpURLConnection

This post includes the usage and implementation of HttpURLConnection to download a file from a URL along with sending the required headers with the http request. Through this post you will also learn to send custom headers along with the request to your http url.

The usage and implementation of HttpURLConnection is very simple as follows:

1. In your project, just add the following method where you want to download the file. Just pass the url from which you want to download the file, as the parameter to the below method.

private void downloadFileFromHttpURL(String your_url){
            
            URL url = new URL(your_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // default headers for the request
            connection.addRequestProperty("Content-Type", "application/json");

            // custom headers for the request
            connection.addRequestProperty("customHeaderKey1", "HEADER_VALUE");
            connection.addRequestProperty("customHeaderKey2", "HEADER_VALUE");

            // check for the connection of url
            int response = connection.getResponseCode();
            if (response == 200) { // connected to the URL
LogWriter.write("LOG_TAG", "Is downloading..?");     

BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
                // provide the path to save the downloaded file
                FileOutputStream fileStream = new FileOutputStream("YOUR_FILE_PATH");

                // BufferesOutputStream is used to write the downloaded file
                BufferedOutputStream outStream = new BufferedOutputStream(fileStream);

                byte[] buffer = new byte[16384];
                int len = 0;
                while ((len = inStream.read(buffer, 0, 16384)) != -1) {
                    LogWriter.write("LOG_TAG", "Yes downloading..");
                    outStream.write(buffer, 0, len);
                }
                outStream.flush();
                inStream.close();
                outStream.close();
            } else {
                // disconnect from URL if not connected  
                connection.disconnect();
                return null;
            }
            // disconnect from URL when the download is completed  
            connection.disconnect();
    }

That's all.
The above method will download the file from the url and save it to the path provided by you.
There are other option as well that you can use with HttpURLConnection which are follows:
   
      connection.setUseCaches(false);
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");

Note:
HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called.
Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).


Share and comment if any issues.

2 comments:

  1. Haidilao is a famous hot pot restaurant known for its wide variety of food choices. The menu offers fresh ingredients like thinly sliced meat, seafood, vegetables, noodles, and tofu, which you cook yourself in flavorful broths.

    ReplyDelete
  2. Renovlies muur is een soort wandbekleding die wordt gebruikt om muren er glad en netjes uit te laten zien. Het is een sterk, duurzaam materiaal dat op de muur wordt geplakt om scheuren, oneffenheden of oud behang af te dekken.

    ReplyDelete