无法在wp7中发送Toast Push通知

时间:2013-05-07 16:26:42

标签: windows-phone-7 windows-phone-8 windows-phone-7.1 windows-phone

我总是得到404错误。下面是我从wcf服务发送Toast类型的推送通知的完整代码。该消息有什么问题?

        string channelURI = "http://db3.notify.live.net/throttledthirdparty/01.00/AgAAAAQUZm52OjBEMTRBNDEzQjc4RUFBRTY";
        HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(channelURI);

        //Indicate that you'll send toast notifications!
        sendNotificationRequest.ContentType = "text/xml";

        sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
        sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

        sendNotificationRequest.Method = "POST";

        sendNotificationRequest.Headers.Add("X-MessageID",Guid.NewGuid().ToString());

        if (string.IsNullOrEmpty(message)) return "empty cannot be sent";

        //send it
        var msg = string.Format("sample toast message", "Toast Message", "This is from server");

        byte[] notificationMessage =  Encoding.UTF8.GetBytes(msg);
        sendNotificationRequest.ContentLength = notificationMessage.Length;



        //Push data to stream
        using (Stream requestStream = sendNotificationRequest.GetRequestStream())
        {
            requestStream.Write(notificationMessage, 0, notificationMessage.Length);
        }


        //Get reponse for message sending
        HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
        string notificationStatus = response.Headers["X-NotificationStatus"];
        string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
        string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
        return notificationStatus;

1 个答案:

答案 0 :(得分:0)

此代码可以帮助您

private static byte[] prepareToastPayload(string text1, string text2)
    {
        MemoryStream stream = new MemoryStream();

        XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = Encoding.UTF8 };
        XmlWriter writer = XmlTextWriter.Create(stream, settings);
        writer.WriteStartDocument();
        writer.WriteStartElement("wp", "Notification", "WPNotification");
        writer.WriteStartElement("wp", "Toast", "WPNotification");
        writer.WriteStartElement("wp", "Text1", "WPNotification");
        writer.WriteValue(text1);
        writer.WriteEndElement();
        writer.WriteStartElement("wp", "Text2", "WPNotification");
        writer.WriteValue(text2);
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();

        byte[] payload = stream.ToArray();
        return payload;
    }
private void SendMessage(Uri channelUri, byte[] payload, NotificationType notificationType, SendNotificationToMPNSCompleted callback)
    {
        //Check the length of the payload and reject it if too long
        if (payload.Length > MAX_PAYLOAD_LENGTH)
            throw new ArgumentOutOfRangeException(
      "Payload is too long. Maximum payload size shouldn't exceed " + MAX_PAYLOAD_LENGTH.ToString() + " bytes");

        try
        {
            //Create and initialize the request object
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(channelUri);
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "text/xml; charset=utf-8";
            request.ContentLength = payload.Length;
            request.Headers[MESSAGE_ID_HEADER] = Guid.NewGuid().ToString();
            request.Headers[NOTIFICATION_CLASS_HEADER] = ((int)notificationType).ToString();

            if (notificationType == NotificationType.Toast)
                request.Headers[WINDOWSPHONE_TARGET_HEADER] = "toast";
            else if (notificationType == NotificationType.Token)
                request.Headers[WINDOWSPHONE_TARGET_HEADER] = "token";

            request.BeginGetRequestStream((ar) =>
            {
                //Once async call returns get the Stream object
                Stream requestStream = request.EndGetRequestStream(ar);

                //and start to write the payload to the stream asynchronously
                requestStream.BeginWrite(payload, 0, payload.Length, (iar) =>
                {
                    //When the writing is done, close the stream
                    requestStream.EndWrite(iar);
                    requestStream.Close();

                    //and switch to receiving the response from MPNS
                    request.BeginGetResponse((iarr) =>
                    {
                        using (WebResponse response = request.EndGetResponse(iarr))
                        {
                            //Notify the caller with the MPNS results
                            OnNotified(notificationType, (HttpWebResponse)response, callback);
                        }
                    },
                    null);
                },
                null);
            },
            null);
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                //Notify client on exception
                OnNotified(notificationType, (HttpWebResponse)ex.Response, callback);
            }
            throw;
        }
    }

protected void OnNotified(NotificationType notificationType, HttpWebResponse response, SendNotificationToMPNSCompleted callback)
    {
        CallbackArgs args = new CallbackArgs(notificationType, response);
        if (null != callback)
            callback(args);
    }
public class CallbackArgs
{
    public CallbackArgs(NotificationType notificationType, HttpWebResponse response)
    {
        this.Timestamp = DateTimeOffset.Now;
        this.MessageId = response.Headers[NotificationSenderUtility.MESSAGE_ID_HEADER];
        this.ChannelUri = response.ResponseUri.ToString();
        this.NotificationType = notificationType;
        this.StatusCode = response.StatusCode;
        this.NotificationStatus = response.Headers[NotificationSenderUtility.NOTIFICATION_STATUS_HEADER];
        this.DeviceConnectionStatus = response.Headers[NotificationSenderUtility.DEVICE_CONNECTION_STATUS_HEADER];
        this.SubscriptionStatus = response.Headers[NotificationSenderUtility.SUBSCRIPTION_STATUS_HEADER];
    }

    public DateTimeOffset Timestamp { get; private set; }
    public string MessageId { get; private set; }
    public string ChannelUri { get; private set; }
    public NotificationType NotificationType { get; private set; }
    public HttpStatusCode StatusCode { get; private set; }
    public string NotificationStatus { get; private set; }
    public string DeviceConnectionStatus { get; private set; }
    public string SubscriptionStatus { get; private set; }
}
public enum NotificationType
{
    Token = 1,
    Toast = 2,
    Raw = 3
}