php将json发布到远程服务器并获取json结果

时间:2014-01-22 22:37:53

标签: php json curl

我想将json数据发布到远程url,url将返回json格式数据。这是我的代码:

    $post_array=Array(
    "trips"=>array(
        "departure_code"=> "SIN",
        "arrival_code"=> "HKT",
        "outbound_date"=>"2014-02-29",
        "inbound_date"=> "2014-03-05"
        ),
        "adults_count"=> 1
    );

    $content = json_encode($post_array);
    $curl = curl_init($search_url);

    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $result     = curl_exec($curl);
    //$response   = json_decode($result);
    var_dump($result);
    curl_close($curl);

结果应该是:

{
  "id": "pNQFapkhRQ6ZYxql4MQDbQ",
  "key": "[SIN:HKT:2014-01-29:2014-02-05]~1~0~XX~FI",
  "trips": [
    {
        "id": "SIN:HKT:2014-01-29:2014-02-05",
        "departure_code": "SIN",
        "departure_name": "Singapore",
        "trip_type": "standard"
    }
  ],
 "cabin": "economy",
 "adults_count": 1,
}

我遇到string(35) "{"message":"Problems parsing JSON"}"错误。谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

什么是$ search_url? 你有这项服务的文件吗?

尝试更改此行:

curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));

为:

curl_setopt(
    $curl,
    CURLOPT_HTTPHEADER,
    array(
        "Content-type: application/json",
        "Content-Length: ".strlen($content)
    )
);

答案 1 :(得分:0)

我在这里向您展示cURL

的简单演示
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                                            'Content-Type:application/json',
                                            'Content-Length:'.strlen($data_string)

                                        ));

$json_response = curl_exec($curl);
$curl_errorno = curl_errno($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);