[英]How to send JSON data in cURL in PHP
我有 Nodejs 服務器的其余 API,我正在嘗試使用 PHP 對它進行 POST 調用。
我的php代碼是:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
我試過用不同形式的數據調用這個函數:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
或者
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
但是在 Node.js 的服務器端,當我控制台 log req.body 時,我得到這樣的數據:
{ '{"_id":"111"}': '' }
我應該如何在 PHP 中傳遞數據,以便我可以在 node.js 中獲得正確的 obj ,即:
{ '_id': '111' }
見PHP文檔: http : //php.net/manual/en/function.curl-setopt.php
CURLOPT_POST :
TRUE 執行常規 HTTP POST。 此 POST 是普通的application/x-www-form-urlencoded類型,最常用於 HTML 表單。
CURLOPT_POSTFIELDS :
如果 value 是一個數組,則 Content-Type 標頭將設置為multipart/form-data 。
因此,您可以將http_build_query()
返回的查詢字符串傳遞到CURLOPT_POSTFIELDS
:
post_url('/CCTRequest/get', http_build_query($g, null, '&'));
並刪除curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
. (實際上,變量應該是$ch
,但是您輸入了$curl
,因此該行不起作用。)
另一種方式,你可以替換curl_setopt($ch, CURLOPT_POST, 1);
與curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
,它可以防止數據被自動編碼。 然后發送json_encode()
數據。
您在代碼中有一個錯字,這將阻止它設置標題$curl
應該是$ch
:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
您還需要取消注釋 CURLOPT_RETURNTRANSFER。
function post_url($apiRoute, $data) {
$request_url = 'www.example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
我已經通過使用http_build_query($g, null, '&')
制作數據解決了。
$g = array("_id" => "111");
$g = http_build_query($g, null, '&');
$postapiresponse = post_url('/CCTRequest/get', $g);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.