如何在Guzzle http中添加标题

raj*_*esh 3 php laravel guzzle guzzlehttp laravel-5.5

我正在构建一个小应用程序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());
    }
}
Run Code Online (Sandbox Code Playgroud)

但这给了我错误:

未定义的属性:Symfony\Component\HttpFoundation\HeaderBag :: $ access_token

请查看截图:

Guzzle HTTP客户端错误

此外,当在控制台中通过浏览器进行调用时,它给出了同样的错误:

浏览器控制台错误

请帮帮我,谢谢.

Web*_*ion 8

试试这段代码

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();
Run Code Online (Sandbox Code Playgroud)