0

我正在尝试一个 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 响应。我的问题在哪里?谢谢你。

4

1 回答 1

1

我假设你使用的是 Guzzle 6。request()方法只有 3 个参数,所以你应该合并你的两个数组。

像这样的东西:

$response = $client->request('POST', $URL, [
    'form_params' => $fields,
    'headers'=> [
        'Authorization' => 'key='.$api_access_key,
        'Content-Type' => 'application/json'
]]);
于 2016-08-08T19:15:56.677 回答