Encode URL string

The example below encode a URL string. Be sure to check java docs as each library handles escaping URLs is similar but different. In the set up method we will reference a URI that each of the snippet will use.

Setup

private static final String URL_TO_ESCAPE = "http://www.leveluplunch.com?somevar=abc123&someothervar";

Straight up Java

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396. In this example we want to encode the URL not form encoding using java. This method doesn't lend itself to be reusable unless you are going to wrap the method that performs this behavior already.

@Test
public void escape_url_with_straight_java () throws UnsupportedEncodingException {

    String urlEscaped = URLEncoder.encode(URL_TO_ESCAPE, "UTF-8")
                .replaceAll("\+", "%20")
                .replaceAll("\%21", "!")
                .replaceAll("\%27", "'")
                .replaceAll("\%28", "(")
                .replaceAll("\%29", ")")
                .replaceAll("\%7E", "~");

    assertEquals("http%3A%2F%2Fwww.leveluplunch.com%3Fsomevar%3Dabc123%26someothervar", urlEscaped);
}

Google Guava

Using guava Escaper we will show how to escape url parameters by calling UrlEscapers.urlPathSegmentEscaper(). This method will escape strings so they can be used within a URL path.

@Test
public void escape_url_with_google_guava () {

    String urlEscaped = UrlEscapers.urlPathSegmentEscaper().escape(URL_TO_ESCAPE);
    assertEquals("http:%2F%2Fwww.leveluplunch.com%3Fsomevar=abc123&someothervar", urlEscaped);
}

Apache Commons

Using apache common's URLCodec we will call encode method which will encodes a string into its URL safe form.

@Test
public void escape_url_with_apache_commons () throws EncoderException {

    URLCodec codec = new URLCodec();
    String urlEscaped = codec.encode(URL_TO_ESCAPE);

    assertEquals("http%3A%2F%2Fwww.leveluplunch.com%3Fsomevar%3Dabc123%26someothervar", urlEscaped);
}

Spring Framework

In this snippet we will encodes the given URI path string so it is safe to be used within a given URL using Springframework. If you are using Java 7 you can use StandardCharsets OR use Guava Charsets. It is quite possible that the Guava Charset version could become deprecated in future releases.

@Test
public void escpae_url_with_spring () throws UnsupportedEncodingException {

    String urlEscaped = UriUtils.encodePath(URL_TO_ESCAPE, Charsets.UTF_8.toString());

    assertEquals("http://www.leveluplunch.com%3Fsomevar=abc123&someothervar", urlEscaped);
}