如何将带有数据的http标头发送到rest Api codeigniter?

Posted

技术标签:

【中文标题】如何将带有数据的http标头发送到rest Api codeigniter?【英文标题】:How to send http header with data to rest Api codiegniter? 【发布时间】:2016-05-20 07:31:05 【问题描述】:

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

我在书本表中有所有书籍详细信息,我想获取所有书籍。

但我有 5 个 http 标头可以访问它们。

Client-Service,Auth-Key,Content-Type,User-ID,Authorization

获取详细信息的网址:

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 标头发送到 rest api 页面并使用 codeigniter 获取所有数据?

【问题讨论】:

PHP cURL custom headers的可能重复 使用工程师先生提到的curl 【参考方案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);

【讨论】:

我如何将来自 url 的响应存储在变量中? i print_r($buffer);然后我得到了 HTTP/1.1 200 OK 日期:2016 年 2 月 10 日星期三 10:55:04 GMT 服务器:Apache/2.4.10 (Unix) OpenSSL/1.0.1j PHP/5.6.3 mod_perl/2.0.8-dev Perl/ v5.16.3 X-Powered-By: PHP/5.6.3 Content-Length: 120 Content-Type: application/json; charset=UTF-8 ["id":"3","title":"Go Programming","author":"Google","id":"1","title":"Codeigniter Rest API ","author":"Momo Baruno"] 。我只想要 json 数据

以上是关于如何将带有数据的http标头发送到rest Api codeigniter?的主要内容,如果未能解决你的问题,请参考以下文章

发送带有 http 标头的 curl 请求

错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法删除标头

我收到“错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头”

节点 JS:错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头

ERR_HTTP_HEADERS_SENT:在 ServerResponse 将标头发送到客户端后无法设置标头

将 set-cookie 标头发送到 node.js 中的重定向 url