编程语言
首页 > 编程语言> > php – 如何在Guzzle http中添加标题

php – 如何在Guzzle http中添加标题

作者:互联网

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

但这给了我错误:

Undefined property: Symfony\Component\HttpFoundation\HeaderBag::$access_token

请查看截图:

Guzzle HTTP client error

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

Browser console error

请帮帮我,谢谢.

解决方法:

试试这段代码

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

标签:laravel-5-5,guzzlehttp,guzzle,php,laravel
来源: https://codeday.me/bug/20190828/1748787.html