[英]Can I post both JSON body and POST values at the same time using PHP/CURL?
我有一个Web服务,它接受GET,POST值作为参数。 到目前为止,我以前使用简单的CURL脚本来调用数据,如下所示:
http://localhost/service/API.php?key=some_password&request=some_request&p1=v1&p2=v2
这是使用“ CURLOPT_POSTFIELDS”成功发布的:
$base_args = array(
'key' => 'some_password',
'request' => 'some_request',
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
问题是,我还需要向该服务发布JSON正文。 我发现可以通过使用“ CURLOPT_POSTFIELDS”来完成此操作,但同时发现我无法同时使用POST和JSON。
$data_string ="{'test':'this is a json payload'}";
$ch = curl_init('http://localhost/service/API.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)));
$result = curl_exec($ch);
echo ($result); // string returned by the service.
我可以设置POST值,也可以设置JSON正文,但不能同时设置两者。 有没有办法可以推两种不同类型的值?
尝试通过变量发送json文本:
$data = array('data' => "{'test':'this is a json payload'}", 'key' => 'some_password', 'request' => 'some_request');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
然后在您的API中执行以下操作:
var_dump(json_decode($_POST['data']));
您仍然可以使用其他键/请求变量。
我找不到同时发送POST和JSON正文的任何方式。 因此,解决方法是将POST参数添加为JSON主体的一部分。
$base_args = array(
'key' => '8f752Dd5sRF4p',
'request' => 'RideDetails',
'data' => '{\'test\',\'test\'}',
);
$ch = curl_init('http://localhost/service/API.php');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($base_args));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen(http_build_query($base_args)))
);
$result = curl_exec($ch);
echo ($result);
API可以返回完整的JSON,如下所示:
var_dump(json_decode(file_get_contents('php://input')));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.