PHP JSON请求

时间:2015-07-03 09:46:36

标签: php json api

您好我正在尝试向API发出JSON请求,但我不知道如何,因为我从未使用过类似的东西。如果有人能帮助我,我真的很感激。

以下是我需要提出的请求:

请求有效负载:

{
    "sessionId": "1234567890",
    "availabilityRequest": {
        "checkInDate": "29042014",
        "checkOutDate": "",
        "noRooms": 1,
        "noNights": 1,
        "userType": "leisure",
        "rateType": "standard",
        "roomPreference": [
            {
                "noAdult": 1,
                "noChild": 0
            }
        ],
        "siteCode": [
            "GB0758",
            "GB0746",
            "GB0738",
            "GB0755",
            "GB0742"
        ],
        "includeDisabled": "F"
    }
}

这就是我所做的,但我收到错误Array ( [error] => Array ( [code] => 4007 [message] => Invalid JSON POST data (unable to decode): ) )

       $postData = '{
                "sessionId":"1234567890",
                "availabilityRequest":
                {
                    "checkInDate": "29042014",
                    "checkOutDate": "",
                    "noRooms": 1,
                    "noNights": 1,
                    "userType": "leisure",
                    "rateType": "standard",
                    "roomPreference": 
                        [
                            { "noAdult":1, "noChild":0 }
                        ],
                    "siteCode": 
                        [
                        "GB0758","GB0746","GB0738","GB0755","GB0742"
                        ],
                    "includeDisabled":"F"
                }
            }';

        $ch = curl_init($url);
        curl_setopt_array($ch, array(
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_POSTFIELDS => $postData));

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // Send the request
        $response = curl_exec($ch);

        // Check for errors
        if($response === FALSE){
            die(curl_error($ch));
        }

        // Decode the response
        $responseData = json_decode($response, TRUE);

        // Print the date from the response
        print_r($responseData);

我真的很感激有人可以帮助我。谢谢

2 个答案:

答案 0 :(得分:1)

您的JSON无效。使用http://jsonlint.com/

等工具进行验证

你应该在最后加一个}来关闭它。然后你将拥有一个有效的JSON。

答案 1 :(得分:0)

我无法对此进行测试,因为我没有测试它的URL,但您可以尝试设置标题。

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($postData)));