如何在Rest Server API中获取/设置Header?

Abd*_*nan 2 php codeigniter codeigniter-2 codeigniter-restserver

我有一个chriskacerguis Rest服务器,它通常像API服务器那样监听客户端请求.基于客户端请求我想要仅在标头中向客户端发送/响应一些数据.

我的问题是:

  1. 我如何首先访问客户端标头?

    然后

  2. 如何在Rest Server中设置Header?

这是我向REST SERVER发送请求的方式:

function request_curl($url = NULL) {
        $utc = time();
        $post = "id=1&CustomerId=1&amount=2450&operatorName=Jondoe&operator=12";
        $header_data = array(
            "Content-Type: application/json",
            "Accept: application/json",
            "X-API-KEY:3ecbcb4e62a00d2bc58080218a4376f24a8079e1",
            "X-UTC:" . $utc,
        );
        $ch = curl_init();
        $curlOpts = array(
            CURLOPT_URL => 'http://domain.com/customapi/api/clientRequest',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $header_data,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $post,
            CURLOPT_HEADER => 1,
        );
        curl_setopt_array($ch, $curlOpts);
        $answer = curl_exec($ch);
        // If there was an error, show it
        if (curl_error($ch)) {
            die(curl_error($ch));
        }

        curl_close($ch);
        echo '<pre>';
        print_r($answer);
        echo '</pre>';
    }
Run Code Online (Sandbox Code Playgroud)

下面是我的REST SERVER函数,它监听请求并响应标头:

public function clientRequest_post() {
        // Getting Post Data
        $entityBody = file_get_contents('php://input', 'r');
       $this->response($entityBody,200);
      //getting header data ,no idea 
    }
Run Code Online (Sandbox Code Playgroud)

Sye*_*jid 7

可以尝试php函数getallheaders(),它将为您获取所有标题数据.如果要将其转换为数组,请使用foreach.

所以这将获得标题数据并将其转换为数组

$headers=array();
foreach (getallheaders() as $name => $value) {
    $headers[$name] = $value;
}
Run Code Online (Sandbox Code Playgroud)

现在,如果你想获取body并将其转换为数组

$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
Run Code Online (Sandbox Code Playgroud)

最终的功能看起来像这样......

public function clientRequest_post() {

    $headers=array();
    foreach (getallheaders() as $name => $value) {
        $headers[$name] = $value;
    }

    $entityBody = file_get_contents('php://input', 'r');
    parse_str($entityBody , $post_data);


    $this->response($entityBody, 200);


}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我假设$this->response($entityBody,200);会为你生成响应.祝你好运