-1

我是 Slim Framework 3 的新手。我在访问具有 Api Key 标头值的 Web 服务时遇到问题。我有一个 Api Key 值并想访问 Web 服务以获取 JSON 数据。这是我的苗条获取方法代码:

$app->get('/getbooking/{id}', function (Request $request, Response $response, $args) {
  $id = $args['id'];
  $string = file_get_contents('http://maindomain.com/webapi/user/'.$id);


  //Still confuse how to set header value to access the web service with Api Key in the header included.
});

我已经尝试使用 Postman(chrome 应用程序)中的 Web 服务进行访问,我得到了结果。我使用 GET 方法并为 Api Key 设置 Headers 值。

但是如何在 Slim 3 中设置 Headers 值来访问 Web 服务呢?

感谢提前:)

4

1 回答 1

2

这实际上与 Slim 没有任何关系。有多种方法可以在 PHP 中发出 HTTP 请求,包括流 (file_get_contents())、curl 和Guzzle等库。

您的示例使用file_get_contents(), 因此要在此处设置标题,您需要创建一个上下文。像这样的东西:

$app->get('/getbooking/{id}', function (Request $request, Response $response, $args) {
  $id = $args['id'];  // validate $id here before using it!

  // add headers. Each one is separated by "\r\n"
  $options['http']['header'] = 'Authorization: Bearer {token here}';
  $options['http']['header'] .= "\r\nAccept: application/json";

  // create context
  $context = stream_context_create($options);

  // make API request
  $string = file_get_contents('http://maindomain.com/webapi/user/'.$id, 0, $context);
  if (false === $string) {
    throw new \Exception('Unable to connect');
  }

  // get the status code
  $status = null;
  if (preg_match('@HTTP/[0-9\.]+\s+([0-9]+)@', $http_response_header[0], $matches)) {
      $status = (int)$matches[1];
  }

  // check status code and process $string here
}
于 2016-12-30T12:00:58.287 回答