PHP cURL RESTful请求

时间:2013-04-19 03:51:50

标签: php rest curl

我在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);
 ?>

1 个答案:

答案 0 :(得分:0)

可能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);

但是如果服务器获得多个变量而不是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);