【问题标题】:How to set multiple header value in Slim Framework 3 to a web service with api key?如何将 Slim Framework 3 中的多个标头值设置为具有 api 密钥的 Web 服务?
【发布时间】:2016-12-30 20:06:14
【问题描述】:

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

$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 服务?

感谢您的提前:)

【问题讨论】:

  • 我认为 Alin Purcaru 在这里的回答会对你有所帮助stackoverflow.com/questions/35439409/…
  • 你想访问'http://maindomain.com/webapi/user/'.$id url 在请求中设置自定义标头吗?

标签: php json slim slim-3


【解决方案1】:

这实际上与 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
}

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多