【问题标题】:How to send http header with data to rest Api codiegniter?如何将带有数据的http标头发送到rest Api codeigniter?
【发布时间】: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 json codeigniter api


【解决方案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 数据
猜你喜欢
  • 2018-02-19
  • 2017-08-08
  • 2016-03-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 2019-08-26
  • 1970-01-01
  • 2016-11-10
相关资源
最近更新 更多