如何使用内容类型为的 PHP curl 发送原始 JSON application/x-www-form-urlencoded
?
让我解释:
我正在与一个接受HTTP POST请求的网络服务器通信,该请求使用 JSON 对象作为请求的主体,通常我们习惯于查看 HTTP 查询参数。
在我的情况下,我需要发送具有以下内容类型的请求
内容类型:application/x-www-form-urlencoded
正文必须是原始 JSON。
所以,有很多可能性。我尝试了以下方法:
<?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);
?>
我也试图逃避json_encode()
:
...
CURLOPT_POSTFIELDS => "\"" . json_encode($data_array) . "\"" ,
...
如果服务器能够解析 html 参数,我可以这样做:
...
CURLOPT_POSTFIELDS => http_build_query($data_array)
...
但是,事实并非如此,我需要一种解决方法。
请注意,更改内容类型将不起作用。我尝试使用text/plain
,但服务器不接受它。