25 August 2005

Encoding URLs

If you're going to reference URLs in a Web page generated through code, you need to encode the search part of those URLs to have acceptably escaped HTML characters. In Java you can do the following:

import java.lang.*;
import java.net.*;

// Copy our raw URL.
String encodedURL = rawURL;

// Determine if the URL contains a query.
URL url = new URL(rawURL);
if (url.getQuery() != null) {
    // Encode only the query part.
    int queryIndex = rawURL.indexOf(url.getQuery());
    encodedURL =
        rawURL.substring(0, queryIndex) +
        url.getQuery().replaceAll("&", "&");

Friday 26 August 2005

Code changed above. Instead of using URL.Encode() to encode the query, just replace ampersands with their HTML escape. We don't want any equal signs encoded.

[ posted by sstrader on 25 August 2005 at 11:56:02 AM in Programming ]