How do I connect to a URL using HttpURLConnection when there are spaces in the name of the URL?

Tim Rohaly



A space is a reserved character in a URL; it is illegal to have a space character as part of a URL. According to the URL specification (RFC 2396), reserved characters must be escaped. In your particular case, this means replacing the spaces with the plus sign "+".

Spaces can often occur in strings returned to the server by an HTML form, since a user might enter arbitrary text.

You may URL-encode a string using the java.net.URLEncoder class. e.g.

    String path = URLEncoder.encode("My Document.html");

Will return the string "My+Document.html". Be sure not to encode the entire URL - just do the portion that contains reserved characters.