如何使用php和cURL从Web服务获得响应

时间:2016-05-20 07:28:04

标签: php rest curl

我正在尝试使用cURL和PHP连接到Web服务。这是我的代码,以及用户输入的表单。:

<?php
if (isset($_POST['submit'])) {
    date_default_timezone_set('Europe/Sofia');
    $hotelID = 1;
    $userName = 'admin';
    $password = 'admin';
    $url = 'http://serviceurl.com/someservice/freerooms.svc';
    $requestTime = date('d.m.Y H:m:s');
    $tempFromDate = date_create($_POST['fromDate']);
    $tempToDate = date_create($_POST['toDate']);
    $fromDate = date_format($tempFromDate, 'd.m.Y H:m:s' );
    $toDate = date_format($tempToDate, 'd.m.Y H:m:s' );
    $data = array(
        'fromDate' => $fromDate,
        'toDate' => $toDate,
        'hotelID' => $hotelID,
        'requestTime' => $requestTime,
        'userName' => $userName,
    );
    $token = md5(md5($password . $requestTime));

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    echo $token . '<br>';
    echo curl_setopt($ch, CURLOPT_HTTPHEADER, array('Bearer: ' . $token));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    $response = curl_exec($ch);
    if (!$response) {
        $error = curl_error($ch);
    }
    curl_close($ch);

    $result = json_decode($response,true);
    print_r($result);

}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Site</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="wrapper" class="col-md-10 col-md-offset-1" style="position: absolute; top: 40%; left: 20%;">
    <div id="form-messages">
        <?php
        if(isset($error)) {
            echo '<b>Error: </b>' . $error;
        } else {
            $error = null;
        }
        ?>
    </div>
    <form action="" method="post" class="form-inline" id="form">
        <div class="form-group">
            <input type="date" name="fromDate" required>
        </div>
        <div class="form-group">
            <input type="date" name="toDate" required>
        </div>
        <button type="submit" name="submit">Submit</button>
    </form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
</body>
</html>

问题是,我无法从后端访问该服务。维护它的所有人都告诉我,应该提交的数据的格式,以及响应将采用JSON格式。这是预订酒店房间。我被告知我应该在标题中提交数据以及令牌。当我提交此代码时,我得到一个空响应,并显示错误,指出令牌是INVALID。这是我第一次使用cURL和RESTful服务,所以欢迎任何帮助。

0 个答案:

没有答案