Php 如何在Slim Framework 3中为具有api密钥的web服务设置多个标头值?
我是Slim Framework 3的新手。我在访问具有Api密钥头值的web服务时遇到问题。我有一个Api键值,希望访问web服务以获取JSON数据。以下是我的slim get方法代码:Php 如何在Slim Framework 3中为具有api密钥的web服务设置多个标头值?,php,json,slim,slim-3,Php,Json,Slim,Slim 3,我是Slim Framework 3的新手。我在访问具有Api密钥头值的web服务时遇到问题。我有一个Api键值,希望访问web服务以获取JSON数据。以下是我的slim get方法代码: $app->get('/getbooking/{id}', function (Request $request, Response $response, $args) { $id = $args['id']; $string = file_get_contents('http://maindo
$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键设置Headers值
但是如何在Slim 3中设置Headers值来访问web服务呢
感谢您的帮助:)这实际上与Slim没有任何关系。有多种方法可以从PHP中发出HTTP请求,包括streams(file_get_contents())、curl和库,如 您的示例使用了
file\u get\u 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
}
我认为Alin Purcaru在这里的回答将对您有所帮助,您想访问
http://maindomain.com/webapi/user/“.$id
url是否在请求中设置自定义标题?