How can I send a raw JSON using PHP curl with a content type of application/x-www-form-urlencoded
?
Let me explain:
I’m communicating with a webserver that accepts HTTP POST requests with a JSON object as the body of the request where normally we are used to seeing HTTP query parameters.
In my situation, I need to send a request with the following content-type
Content-Type: application/x-www-form-urlencoded
The body must be raw JSON.
So, there are many possibilities. I tried the following:
<?php
$server_url = "http://server.com";
$curl = curl_init($server_url);
$data_array = array("a"=> "a_val", "b" => array("c"=>"c_val", "d"=>"d_val") );
$options = array(
CURLOPT_POST => TRUE,
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
CURLOPT_POSTFIELDS => json_encode($data_array),
CURLOPT_COOKIEJAR => realpath('tmp/cookie.txt'),
CURLOPT_COOKIEFILE => realpath('tmp/cookie.txt')
);
curl_setopt_array($curl, $options);
$return = curl_exec($curl);
var_dump($return);
curl_close($curl);
?>
I also tried to escape the json_encode()
:
...
CURLOPT_POSTFIELDS => "\"" . json_encode($data_array) . "\"" ,
...
If the server was able to parse html parameters I could just do this:
...
CURLOPT_POSTFIELDS => http_build_query($data_array)
...
However, that is not the case and I need a workaround.
Please note that changing the content-type won’t work. I tried using text/plain
, but the server would not accept it.