如何发送带有数据的http头来休息Api codiegniter?

时间:2016-02-10 04:31:17

标签: php json codeigniter api

我想将http标头发送到Api并获取json响应。

我在书籍表中列出了所有书籍细节,我希望得到所有书籍。

但我有5个http标头才能访问它们。

客户服务,验证密钥,内容类型,用户ID,授权

网址获取详细信息:

http://127.0.0.1/RestApi/index.php/book/

控制器代码:

    public function index() {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method != 'GET') {
        json_output(400, array('status' => 400, 'message' => 'Bad request.'));
    } else {
        $check_auth_client = $this->MyModel->check_auth_client();
        if ($check_auth_client == true) {
            $response = $this->MyModel->auth();
            if ($response['status'] == 200) {
                $resp = $this->MyModel->book_all_data();
                json_output($response['status'], $resp);
            }
        }
    }
}

型号代码:

public function book_all_data()
{
    return $this->db->select('id,title,author')->from('books')->order_by('id','desc')->get()->result();
}

我想访问按钮点击访问但是如何将http标头发送到其他api页面并使用codeigniter获取所有数据?

1 个答案:

答案 0 :(得分:1)

使用CURL设置标头。见下面的例子。希望它能帮到你

$headers = array(
                 'Client-Service:CLIENT_SERVICE_DETAIL',
                 'Auth-Key:YOUR_AUTH_KEY',
                 'Content-Type:YOUR_CONTENT_TYPE',
                 'User-ID:YOUR_USER_ID',
                 'Authorization:YOUR_AUTHORIZATION',   
                 );

$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, YOUR_URL);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_HEADER, 1); 
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);

$buffer = curl_exec($curl_handle);
$header_size = curl_getinfo($curl_handle, CURLINFO_HEADER_SIZE);
$body = substr($buffer, $header_size);

curl_close($curl_handle);