如何在不使用cURL的情况下通过php发送GCM消息?

3

我正在使用以下代码向gcm服务器发出HTTP POST请求。但是,该代码总是返回“未经授权的错误401”。我阅读了一些关于head部分的资料,但仍然无法弄清楚问题所在。有人能告诉我错在哪里吗?是否有其他方法可以发送gcm消息?非常感谢您的帮助。

$api_key = "AIzaSyBhuPSdHmq6-************_qxSJr8d0";

$message = array("msg_url" => $msg_url, "msg_title" => $msg_title);

$url = 'https://android.googleapis.com/gcm/send';

$fields = array('registration_ids'  => $ids,'data'=> array( "message" => $message ));

$headers = array('Authorization: key=' . $api_key,'Content-Type: application/json');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'=> $headers ,
        'method'  => 'POST',
        'content' => json_encode($fields),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

也许问题出在你的 API 密钥上。试着在这里进行测试:http://helmibaraja.com/gcm_demo.html。 - Eran
API密钥没有问题。我已经用cURL方法测试过了,它完全正常工作。但是出于某些服务器原因,我不想使用cURL方法。有没有其他替代的方法呢?你提供的链接使用了cURL。 - Rahul
1个回答

5

我用我的API密钥测试了你的代码。我能够向GCM发送请求并且得到了正确的响应。看起来是你的API密钥出了问题。

<?php

$msg_url = "http://msg.com";

$msg_title = "message_title";

$ids = array('reg_id_1', 'reg_id_2'); 

$api_key = "AIzaSyBhuPSdHmq6-************_qxSJr8d0";

$message = array("msg_url" => $msg_url, "msg_title" => $msg_title);

$url = 'https://android.googleapis.com/gcm/send';

$fields = array('registration_ids'  => $ids,'data'=> array( "message" => $message ));

$headers = array('Authorization: key=' . $api_key,'Content-Type: application/json');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'=> $headers ,
        'method'  => 'POST',
        'content' => json_encode($fields),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接