php 如何发送HTTP头与数据休息API codegniter?

7lrncoxx  于 2022-12-10  发布在  PHP
关注(0)|答案(2)|浏览(202)

我想发送http头到API并获得json响应。
我在“书籍”表中有所有书籍详细信息,我想获取所有书籍。
但是我有5个http头来访问它们。

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

获取详细信息的URL:
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?

nwlls2ji

nwlls2ji1#

使用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);
fjnneemd

fjnneemd2#

CURLOPT_HEADER         => false,  // don't return headers

相关问题