tags:

views:

24

answers:

1

Many languages allow one to pass an array of values through the url. I need to , for various reasons, directly construct the url by hand. How is an array of values urlencoded?

+2  A: 

It looks like the content in the form of MIME-Type: application/x-www-form-urlencoded.

This is the default content type. Forms submitted with this content type must be encoded as follows:

  1. Control names and values are escaped. Space characters are replaced by +, and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by %HH, a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A).
  2. The control names/values are listed in the order they appear in the document. The name is separated from the value by = and name/value pairs are separated from each other by &.

Which is used for the POST. To do it for the GET, you'll have to append a ? after your URL, and the rest is almost equal. In the comments, mdma states, that the URL may not contain a + for a space character. Instead use %20.

So an array of values:

http://localhost/someapp/?0=zero&1=valueone%20withspace&2=etc&3=etc

Often there is some functionality in libraries that will do the URL encoding for you (point 1). Point two is easily implementable by looping over your array, building the string, appending the index, =, the URL encoded value and when it's not the last entry an &.

Pindatjuh
I only found out recently that form encoding a URL is actually wrong, but a common error (most major browsers do this.) The '+' is the difference. The URL should follow the RFC1738. Form encoding is allowed in POST body but not in GET query params - the URL should just use URL encoding. I know this is splitting hairs - this is fyi. :)
mdma
Thanks! What about the Google search engine: `/search?q=hello+world` which is a GET, but uses the `+`? It seems to work, but it is not "really allowed", following specifications... I understand the split hairs now.
Pindatjuh
+1 : Most browsers produce it and probably 99% of servers accept it, since they treat the URL query params as form encoded. And I've done it myself, but I never really liked the use of + to represent space - seems like a hack.
mdma