x-www-form-urlencoded Vs json HTTP POST

user1125394 picture user1125394 · Jul 1, 2012 · Viewed 21.4k times · Source

It's hard to decide,
currently I'm sending data as x-www-form-urlencoded with php lib curl with

curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($this->arguments));

or

curl_setopt($curl, CURLOPT_POSTFIELDS, $this->arguments);

first question: second one seems to be larger content length, first solution is probably better?

It's practical for flat messages like:

{
    "name": "John",
    "token": "2121232145",
    "code": "7",
    "data": "Hello"
}

But I can have also a data field that represent a object, in this case I was enconding it, but doing that (url encoding a Json) is terribly verbose and ugly messages,

On the other side I tried sending it as application/json content-type

curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($this->arguments));

the content-length is larger for small messages but with embedded json, it's clearly better

But x-www-form-urlencoded is also close to the forms data I need to send, except when a json is embedded

It would not be elegant to have 2 differents servlet parse methods depending on the content types, so is there another option?

Answer

pinepain picture pinepain · Nov 19, 2012

Here you can read similar discussion about formats.

If the structure of encoded data is guaranteed to be a flat list of name-value pairs, x-www-form-urlencoded seems sufficient. If the structure could be (arbitrarily) complex (e.g. nesting lists or associative arrays), then definitely use JSON.

As for me, I'm the KISS adept. In your situation JSON/XML/whatever is extra costs in time, memory and CPU cycles. x-www-form-urlencoded data combine readability and compactness so i can bet it's your choice.