Android HttpURLConnection


Android HttpURLConnection Tutorial and Examples.

In this piece we explore HttpURLConnection, android and java's standard networking class.

As a networking class HttpURLConnection can be to make HTTP requests over the web.

HttpUrlconnection is a UrlConnection for HTTP used to send as well receive data over the web. These data may be of any type and length.

HttpURLConnection was added in android 1.0 and is a URLConnection with support for HTTP-specific features. Like its parent URLConnection, it resides in the java.net package. This class allows us do networking easily and is the standard networking library in android.

HttpUrlConnection can also be used to send and receive streams whose length isn’t known in advance.

To be used,we obtain a new HttpUrlconnection object by calling url.openConnection() and casting to HttpUrlConnection.

If we open a connction to a url with "https" scheme,this returns HttpsUrlConnection.

Here is a simple usage of HttpURLConnection to download a webpage:

   URL url = new URL("http://www.google.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }

For example, to retrieve the webpage at http://www.android.com/:

   URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }
Posting Content

To post some content to a web server, first you have to configure the connection for output using setDoOutput(true).

For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     urlConnection.setDoOutput(true);
     urlConnection.setChunkedStreamingMode(0);

     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
     writeStream(out);

     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
   } finally {
     urlConnection.disconnect();
   }
HTTP Authentication

HttpURLConnection supports HTTP basic authentication. You can use Authenticator to set the VM-wide authentication handler:

  Authenticator.setDefault(new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication(username, password.toCharArray());
     }
   });
Sessions with Cookies

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:

  CookieManager cookieManager = new CookieManager();
   CookieHandler.setDefault(cookieManager);

Quick HttpURLConnection Examples

1. Get Byte Array From Server

The aim is to get a byte array when supplied a URL string. We first instantiate the java.net.URL with the url.

Once we have the java.net.URL instance, we use it to open a connection which returns us a URLConnection.

This URLConnection is the parent class of HttpURLConnection, so we just cast it to our HttpUrlConnection.

Here's the full method:

public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();

    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() + ": with " +
                    urlSpec);
        }

        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
}
2. Ping URL

This method will ping the given url for availability. It will send a HEAD request and return true if the response code is in the 200 - 399range.

private static final String HEAD_REQUEST_METHOD = "HEAD";
/**
 * @param url the url to be pinged.
 * @param timeout_millis the timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return {@code true} if the given {@code url} has returned response code within the range of {@code 200} - {@code 399} on a HEAD request, {@code false} otherwise
 */
public static boolean ping(final URL url, final int timeout_millis) {

    try {
        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(timeout_millis);
        connection.setReadTimeout(timeout_millis);
        connection.setRequestMethod(HEAD_REQUEST_METHOD);

        final int response_code = connection.getResponseCode();
        return HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_BAD_REQUEST;
    }
    catch (IOException exception) {
        return false;
    }
}
3. Download Image Using HttpURLConnection

There are many complex image downloaders and loaders out there. But we also have to know how to implement our own with basic HttpURLConnection and AsyncTask

Here's how we can download a bitmap and return it. To use with AsyncTask all you have to do is call this method inside your doInBackground() method, then receive the bitmap in the onPostExecute() method, where then you can render it into your imageview.

/**
 * Download the image from the given URL
 * @param urlString the URL to download
 * @return a bitmap of the downloaded image
 */
private Bitmap downloadImage(String urlString) {
    Bitmap bmp = null;

    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        InputStream is = conn.getInputStream();
        bmp = BitmapFactory.decodeStream(is);
        if (bmp != null) {
            return bmp;
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return bmp;
}
4. Two methods to get Domain Names

You can reuse these two methods to get domain name for either SSL sites and Non-SSL sites.

All you have to do is pass the string url.

public static String getDomainName(String url) {
        boolean ssl = url.startsWith(Constants.HTTPS);
        int index = url.indexOf('/', 8);
        if (index != -1) {
            url = url.substring(0, index);
        }

        URI uri;
        String domain = null;
        try {
            uri = new URI(url);
            domain = uri.getHost();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        if (domain == null || domain.isEmpty()) {
            return url;
        }
        if (ssl)
            return Constants.HTTPS + domain;
        else
            return domain.startsWith("www.") ? domain.substring(4) : domain;
    }

    public static String getDomainName2(String url) {

        URI uri;
        String domain = "";
        try {
            uri = new URI(url);
            domain = uri.getHost();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if(domain==null){
            return "";
        }
        return domain;
    }
5. How to get Protocol when provided a url
    public static String getProtocol(String url) {
        int index = url.indexOf('/');
        return url.substring(0, index + 2);
    }
6. How to Check if a given URL can respond to a HTTP request

This method will Check if a URL exists and can respond to an HTTP request.

The first parameter is the url to check. Then we return True if the URL exists, false if it doesn't or an error occured.

public static boolean checkURL(String url) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        return false;
    }
}
7. How to get ContentTypes(and Cache them)

We want to see how we can get Content Types. We will be caching our results throughout the runtime of our app.

Start by importing HttpURLConnection, URL, and HashMap.

The HttpURLConnection is of course our networking class. The URL will allow us convert a simple string into a URL we can actually connect.

The HashMap will be used to cache our content types.

Let's start by creating a class:

public final class HttpUtil {..}

You can see we have used the final modifier. This keyword is a non-access modifier applicable only to a variable, a method or a class.

A final class is a class that can't be extended or derived from. This is a utility class and we don't want it extended.

We will then have two constants:

    static public final int TIMEOUT_DIRECT = 5 * 1000;
    private static final HashMap<URL, String> cachedContentTypes
            = new HashMap<URL, String>();

The TIMEOUT_DIRECT is our default timeout for direct URL connections. On the other hand cachedContentTypes will cache our retrieved content types.

Now we will have two methods responsible for getting us the content types.

First we are receiving a URL object. We will check first if that URL is already contained in our cached contents. If it is then we just get it from there. Otherwise we open our connection, set it's properties and return later our content type.

    /**
     * Gets the content type reported for the given URL.
     * Results are cached throughout runtime.
     */
    public static String getContentType(URL uri) {
        if (!cachedContentTypes.containsKey(uri)) {
            String contentType = null;
            try {
                HttpURLConnection c = (HttpURLConnection)  uri.openConnection();
                HttpURLConnection.setFollowRedirects(true);
                c.setConnectTimeout(TIMEOUT_DIRECT);
                c.setReadTimeout(TIMEOUT_DIRECT);
                c.setRequestMethod("HEAD");
                c.connect();
                contentType = c.getContentType();
            } catch (Exception e) { }
            cachedContentTypes.put(uri, contentType);
        }
        return cachedContentTypes.get(uri);
    }
}

Then our second method simply receives a string then we build our URL from that string. Then we can simply reuse the first method.

    /**
     * Gets the content type reported for the given URL.
     * Results are cached throughout runtime.
     */
    public static String getContentType(String uri) {
        String contentType = null;
        try {
            contentType = getContentType(new URL(uri));
        } catch (Exception e) { }
        return contentType;
    }

Just take those two methods and our two constants and add them to our class.

Top Android HttpURLConnection Examples

Let's look at some examples.

Android HttpURLConnection HTTP GET Tutorial.

In this piece we explore some HTTP GET examples. Basicaly how to perform HTTP GET using the HttpURLConnection class.

Let's start.

Android HttpURLConnection HTTP POST Tutorial.

This section contains various examples that allow you make HTTP POST request against a server. We use android's standard networking class HttpURLConection to make our requests.

Android org.JSON and HttpURLConnection Tutorial and Examples.

Android PHP MySQL HttpURLConnection Examples.

MySQL is our database while PHP is the server side language we use. The client code is for android is written in this case in either Java or Kotlin.

Android org.XML and HttpURLConnection Tutorial and Examples.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post