Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: URL encoding for post data

I've been looking at Network.HTTP, but can't find a way to create properly URL encoded key/value pairs.

How can I generate the post data required from [(key, value)] pair list for example? I imagine something like this already exists (perhaps hidden in the Network.HTTP package) but I can't find it, and I'd rather not re-invent the wheel.

like image 219
Clinton Avatar asked Jul 31 '12 02:07

Clinton


2 Answers

Take a look at urlEncodeVars.

urlEncodeVars :: [(String, String)] -> String
ghci> urlEncodeVars [("language", "Haskell"), ("greeting", "Hello, world!")]
"language=Haskell&greeting=Hello%2C%20world%21"
like image 160
icktoofay Avatar answered Sep 30 '22 02:09

icktoofay


If you are trying to HTTP POST data x-www-form-urlencoded, urlEncodeVars may not be the right choice. The urlEncodeVars function does not conform to the application/x-www-form-urlencoded encoding algorithm in two ways worth noting:

  • it encodes a space as %20 instead of +
  • it encodes * as %2A instead of *

Note the comment alongside the function in Network.HTTP.Base:

-- Encode form variables, useable in either the
-- query part of a URI, or the body of a POST request.
-- I have no source for this information except experience,
-- this sort of encoding worked fine in CGI programming.

For an example of a conformant encoding, see this function in the hspec-wai package.

like image 24
Erin Swenson-Healey Avatar answered Sep 30 '22 02:09

Erin Swenson-Healey