我正在尝试通过C#.net向GCM服务器发送消息
我找到了一个很好的例子,我正在尝试使用它
http://www.codewithasp.net/2015/11/send-message-gcm-c-sharp-single-multiple.html
每当我尝试从该行获取响应时,就会出现“远程服务器返回错误:(400) 错误请求。”的问题。 WebResponse wResponse = wRequest.GetResponse();
我试图找出问题所在,我将API代码从服务器更改为Android、浏览器,结果要么是(400)错误请求,要么是(401)未经授权。
不确定我在这里做错了什么,它在示例中看起来非常简单和直接。
非常感谢您的帮助。
以下是代码:
NotificationManager nm = new NotificationManager();
List<string> ls = new List<string>(new string[] { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" });
nm.SendNotification(ls, " Hi.. This is a test","Hi.. Title",1);
这里是类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Net;
using System.Text;
using System.IO;
namespace WebApplication1
{
public class NotificationManager
{
private class NotificationMessage
{
public string Title;
public string Message;
public long ItemId;
}
public NotificationManager()
{
//
// TODO: Add constructor logic here
//
}
public string SendNotification(List<string> deviceRegIds, string message, string title, long id)
{
try
{
string regIds = string.Join("\",\"", deviceRegIds);
string AppId = "AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var SenderId = "1234567890";
NotificationMessage nm = new NotificationMessage();
nm.Title = title;
nm.Message = message;
nm.ItemId = id;
var value = new JavaScriptSerializer().Serialize(nm);
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + regIds + "\"]}";
Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
String response = reader.ReadToEnd();
HttpWebResponse httpResponse = (HttpWebResponse)wResponse;
string status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
if (status == "")
{
return response;
}
else
{
return "";
}
}
catch( Exception ex)
{
return ex.ToString();
}
}
}
}
这是我获取API ID和发送者ID的方法