php Guzzle HTTP - 将授权标头直接添加到请求中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36011790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Guzzle HTTP - add Authorization header directly into request
提问by Zabs
Can anyone explain how to add the Authorization Header within Guzzle? I can see the code below works for adding the username & password but in my instance I just want to add the Authorization header itself
谁能解释一下如何在 Guzzle 中添加授权标头?我可以看到下面的代码可用于添加用户名和密码,但在我的实例中,我只想添加 Authorization 标头本身
$client->request('GET', '/get', ['auth' => ['username', 'password']
The Basic Authorization header I want to add to my GET request :-
我想添加到我的 GET 请求中的基本授权标头:-
Basic aGdkZQ1vOjBmNmFmYzdhMjhiMjcwZmE4YjEwOTQwMjc2NGQ3NDgxM2JhMjJkZjZlM2JlMzU5MTVlNGRkMTVlMGJlMWFiYmI=
采纳答案by Shaun Bramley
From the looks of things, you are attempting to use an API key. To obtain your desired effect, simply pass null
in as the username, like below.
从表面上看,您正在尝试使用 API 密钥。要获得您想要的效果,只需null
作为用户名传入,如下所示。
$client->request(
$method,
$url,
[
'auth' = [
null,
$api_key
],
]
);
回答by Matt D.
I don't know how I missed reading that you were looking for the Basic auth header, but nonetheless hope this helps somewhat. If you are just looking to add the Authorization header, that should be pretty easy.
我不知道我是如何错过阅读您正在寻找 Basic auth 标头的信息,但仍然希望这会有所帮助。如果您只是想添加 Authorization 标头,那应该很容易。
// Set various headers on a request
$client->request('GET', '/get', [
'headers' => [
'Authorization' => 'PUT WHATEVER YOU WANT HERE'
]
]);
I build up my request in Guzzle piece by piece so I use the following:
我在 Guzzle 中逐个建立我的请求,所以我使用以下内容:
$client = new GuzzleHttp\Client();
$request = $client->createRequest('GET', '/get');
$request->addHeader('X-Authorization', 'OAuth realm=<OAUTH STUFF HERE>');
$resp = $client->send($request);
Hope that helps. Also, make sure to include the version of Libraries you are using in the future as syntax changes depending on your version.
希望有帮助。此外,请确保包含您将来使用的库版本,因为语法会根据您的版本而变化。
回答by Agu Dondo
I'm using Guzzle 6. If you want to use the Basic Auth Scheme:
我正在使用 Guzzle 6。如果您想使用基本身份验证方案:
$client = new Client();
$credentials = base64_encode('username:password');
$response = $client->get('url',
[
'headers' => [
'Authorization' => 'Basic ' . $credentials,
],
]);
回答by Grigoreas P.
use GuzzleHttp\Client;
...
...
$client = new Client(['auth' => [$username, $password]]);
$res = $client->request('GET', 'url', ['query' => ['param1'=>$p1, 'param2'=>'sometext']]);
$res->getStatusCode();
$response = $res->getBody();
This creates an authorized client and sends a get request along with desired params
这将创建一个授权的客户端并发送一个获取请求以及所需的参数