[英]PHP cURL RESTful request
我在server.pad.com/authenticate(本地)上有一個RESTful服務器,該服務器采用一個參數並返回JSON。 所以在Laravel中它的authenticate/(:any)
我試圖從ajax請求中獲取數據,並將其發送到服務器並發送回響應。 這是我嘗試過的...
<?php
$json = json_decode($_POST['data'], true);
$url = 'http://service.pad.com/authenticate';
$curl = curl_init($url);
$data = json_encode($json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
echo json_encode($response);
?>
可能是Content-Type: application/x-www-form-urlencoded
問題。
您的$data
使用JSON。 您可以使用CURLOPT_POSTFIELDS設置值,但不能設置var。
如我所見,$ _ POST ['data']位於JSON中。
如果服務器使用JSON獲取單個data
,請嘗試以下操作:
$url = 'http://service.pad.com/authenticate';
$curl = curl_init($url);
$postdata = array( 'data' => $_POST['data'] );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postdata) );
$response = curl_exec($curl);
curl_close($curl);
echo json_encode($response);
但是,如果服務器獲取多個var,而不是JSON,請嘗試以下操作:
$url = 'http://service.pad.com/authenticate';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,
http_build_query( json_decode($_POST['data'], true) )
);
$response = curl_exec($curl);
curl_close($curl);
echo json_encode($response);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.