【问题标题】:guzzlephp 401 unauthorized issueguzzlephp 401 未经授权的问题
【发布时间】:2016-12-14 03:09:49
【问题描述】:

我正在尝试

的 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 响应。我的问题在哪里?谢谢。

【问题讨论】:

    标签: curl guzzle guzzle6


    【解决方案1】:

    我假设你使用的是 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'
    ]]);
    

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 2012-10-02
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 2011-03-06
      • 2018-05-19
      相关资源
      最近更新 更多