guzzlephp 401未经授权的问题

时间:2016-08-08 11:03:18

标签: curl guzzle guzzle6

我正在通过

尝试一个guzzle http post请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
return $result;

标题是

$headers = [
            'Authorization: key=' . $api_access_key,
            'Content-Type: application/json',
        ];

和帖子字段是

$fields = [
            'registration_ids' => $registrationIds,
            'data'             => [
                'title'   => $title,
                'message' => $message,
                'type'    => $type,
            ],
        ];

哪个响应正常并且如预期的那样但是如果我通过guzzlehttp客户端通过

调用此请求
$URL='https://android.googleapis.com/gcm/send';

$client  = new \GuzzleHttp\Client(['http_errors' => false]);

$response = $client->request('POST', $URL,['form_params'=>$fields],
                                 ['headers'=>[
                                  'Authorization' => 'key='.$api_access_key,
                                   'Content-Type' => 'application/json']]);

return $response->getBody()->getContents();

它以401未经授权的方式回应。我的问题在哪里?谢谢。

1 个答案:

答案 0 :(得分:0)

我假设您使用的是Guzzle 6. request()方法has only 3 parameters,因此您应合并两个数组。

这样的事情:

$response = $client->request('POST', $URL, [
    'form_params' => $fields,
    'headers'=> [
        'Authorization' => 'key='.$api_access_key,
        'Content-Type' => 'application/json'
]]);