如何在不使用cURL的情况下在php中发送gcm消息? [英] How to send a gcm message in php without using cURL?
本文介绍了如何在不使用cURL的情况下在php中发送gcm消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码向gcm服务器发出HTTP POST请求。
代码总是返回未授权的错误401。我读到它是关于标题,但无法弄清楚什么是错的。
谁能告诉我什么是错的?
是否有其他方式发送gcm讯息?
任何帮助,将不胜感激。
I'm using the following code to make HTTP POST request to the gcm server. The code always returns "Unauthorized Error 401". I read that it is about the headers but can't figure out whats wrong. Can anyone tell me what's wrong? Is there any other way to send a gcm message? Any help would be appreciated.
$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密钥测试您的代码。我可以向GCM发送请求并获得适当的响应。看起来您的API密钥存在问题
Tested your code with my API key. I am able to send request to GCM and getting proper response. It seems like your API Key is having the problem
<?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);
?>
这篇关于如何在不使用cURL的情况下在php中发送gcm消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文