laravel 如何在 Guzzle http 中添加标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48418527/
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
How to add headers in Guzzle http
提问by rajesh
I'm building a small application in Laravel 5.5
where I'm using Guzzle Http
to get call the api url and get the response, Few of the api calls have certain condition to have headers which works as authorization of the request generated. I'm trying to place the header something like this:
我正在构建一个小型应用程序,在Laravel 5.5
其中我Guzzle Http
用来调用 api url 并获得响应,很少有 api 调用具有某些条件来具有作为生成请求的授权的标头。我正在尝试放置这样的标题:
public function post(Request $request)
{
try {
if ($request->url_method == 'get') {
$request = $this->client->get($request->url, [ 'headers' => [ 'access_token' => $request->headers->access_token]]);
}
else if ($request->url_method == 'post')
{ $request = $this->client->post($request->url, [$request->request_data]); }
else { return response()->json(['data' => 'Invalid Method'],500); }
$response = \GuzzleHttp\json_decode($request->getBody());
return response()->json(['data' => json_decode($response->d)], $request->getStatusCode());
}
catch (ClientException $e) {
return response()->json(['data' => 'Invalid Request.'], $request->getStatusCode());
}
}
But this is giving me errors:
但这给了我错误:
Undefined property: Symfony\Component\HttpFoundation\HeaderBag::$access_token
未定义的属性:Symfony\Component\HttpFoundation\HeaderBag::$access_token
Please checkout the screenshot:
请检查屏幕截图:
Also when calling through the browser in console it gives me the same error:
此外,在控制台中通过浏览器调用时,它给了我同样的错误:
Help me out in this, Thanks.
帮我解决这个问题,谢谢。
回答by Webinion
try this code
试试这个代码
use GuzzleHttp\Client as GuzzleClient;
..
..
..
$headers = [
'Content-Type' => 'application/json',
'AccessToken' => 'key',
'Authorization' => 'Bearer token',
];
$client = new GuzzleClient([
'headers' => $headers
]);
$body = '{
"key1" : '.$value1.',
"key2" : '.$value2.',
}';
$r = $client->request('POST', 'http://example.com/api/postCall', [
'body' => $body
]);
$response = $r->getBody()->getContents();
回答by Shamim Shams
Try to add bearer in all small cases before access token like following -
尝试在访问令牌之前在所有小情况下添加承载,如下所示 -
$access_token = 'bearer '.$request->headers->access_token