views:

564

answers:

4

In a URL that used to request an image on a page (in this case a tracking image) should I encode the spaces using %20 or +.

i.e.

www.mydomain.com?type=xbox%20360

or

www.mydomain.com?type=xbox+360

Our tracking company is expecting the top version, but the Java method URLEncoder.encode("xbox 360","UTF-8") gives the bottom version.

What is the difference? Is one correct?. How can I generate the top version?

+1  A: 

It shouldn't matter, any more than if you encoded the letter A as %41.

However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.

Gary McGill
+9  A: 

Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded: this specifies + for spaces.

URLs are encoded as RFC 1738 which specifies %20.

In theory I think you should have %20 before the ? and + after:

example.com/foo%20bar?foo+bar
Greg
+7  A: 

According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either "%20" or "+". From the section "Query strings" under "Recommendations":

Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.

According to section 3.4 of RFC2396 which is the official specification on URIs in general, the "query" component is URL-dependent:

3.4. Query Component The query component is a string of information to be interpreted by the resource.

   query         = *uric

Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.

It is therefore a bug in the other software if it does not accept URLs with spaces in the query string encoded as "+" characters.

As for the third part of your question, one way (though slightly ugly) to fix the output from URLEncoder.encode() is to then call replaceAll("\\+","%20") on the return value.

Adam Batkin
+1  A: 

You can use either - which means most people opt for "+" as it's more human readable.

Sohnee