2

我有一个chriskacerguis休息服务器,它像 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>';
    }

下面是我的 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 
    }
4

1 回答 1

9

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

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

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

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

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

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

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);


}

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

于 2015-06-13T11:37:21.093 回答