HttpURLConnection and GET query parameters

I regret that JAVA SE still lacks any decent native HTTP client framework! Simple use cases like GET requests with query parameters require handcrafted coding with HttpURLConnection.

This article appeared first at techtavern.wordpress.com.

HttpURLConnection misses methods to set query parameters. There is no URI builder facility as found on Apache HTTP Client. You are on your own.

Therefore, I wrote the applyParameter method that takes care of GET query parameters.

URI baseUri = new URI("www.exemple.com/search");
URI uri = applyParameters(baseUri, "word","java");
HttpURLConnection connection = 
    (HttpURLConnection) uri.toURL().openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestMethod("GET");
connection.connect();
if (connection.getResponseCode() == 
   HttpURLConnection.HTTP_OK) {
   // ...
}

The applyParameters method looks like:

URI applyParameters(URI baseUri, String[] urlParameters)
   StringBuilder query = new StringBuilder();
   boolean first = true;
   for (int i = 0; i < urlParameters.length; i += 2) {
     if (first) {
        first = false;
     } else {
        query.append("&");
     }
     try {
        query.append(urlParameters[i]).append("=")
             .append(URLEncoder.encode(urlParameters[i + 1], "UTF-8"));
     } catch (UnsupportedEncodingException ex) {
        /* As URLEncoder are always correct, this exception
         * should never be thrown. */
       throw new RuntimeException(ex);
     }
   }
   try {
      return new URI(uri.getScheme(), uri.getAuthority(), 
         uri.getPath(), query.toString(), null);
   } catch (URISyntaxException ex) {
     /* As baseUri and query are correct, this exception
      * should never be thrown. */
      throw new RuntimeException(ex);
   }
}

I had to bother about catching two exception that I know that will never be thrown: URISyntaxException and UnsupportedEncodingException. I had to join parameters by hand into a string. I had to care about safe web encoding. Shame on you JAVA!

Fortunately, at least I figured out that the URI constructor allows to append the query string to the base URI.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: