Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Plus sign in GET-Request replaced by space

In Rails 3 (Ruby 1.9.2) I send an request

 Started GET "/controller/action?path=/41_+"

But the parameter list looks like this:

 {"path"=>"/41_ ",
   "controller"=>"controller",
   "action"=>"action"}

Whats going wrong here? The -, * or . sign works fine, its just the +which will be replaced by a space.

like image 974
f00860 Avatar asked Jun 24 '11 07:06

f00860


2 Answers

That's normal URL encoding, the plus sign is a shorthand for a space:

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.

And from the HTML5 standard:

The character is a U+0020 SPACE character
Replace the character with a single U+002B PLUS SIGN character (+).

like image 92
mu is too short Avatar answered Nov 20 '22 07:11

mu is too short


For POST-requests, (in case that's how some of you stumbled upon this question, like me) one might encounter this problem because one has encoded the data in the wrong way on the client side. Encoding the data as application/x-www-form-urlencoded will tell rails to decode the data as it decodes a URL, and hence replace + signs with whitespace, according to the standard RFC1738 as explained by @mu is too short

The solution is to encode the data on the client side as multipart/form-data.

In PHP, using cURL, this is done by taking into consideration the following gotcha:

Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded. http://php.net/manual/en/function.curl-setopt.php

You might wonder why I was using PHP on the client side (that's because the client in my example was another webserver, since I'm working on an API connection.)

like image 3
Magne Avatar answered Nov 20 '22 07:11

Magne