如何在Guzzle http中添加标题

时间:2018-01-24 09:05:20

标签: php laravel laravel-5.5 guzzle guzzlehttp

我正在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());
    }
}

但这给了我错误:

  

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

请查看截图:

default implementation

同样在控制台中通过浏览器进行调用时,它也会出现同样的错误:

Guzzle HTTP client error

在此帮助我,谢谢。

2 个答案:

答案 0 :(得分:7)

试试这段代码

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();

答案 1 :(得分:-2)

尝试在访问令牌之前在所有小案例中添加承载,如下所示 -

$access_token = 'bearer '.$request->headers->access_token