簡體   English   中英

我可以使用PHP / CURL同時發布JSON正文和POST值嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM