2015-12-30 48 views
1

我對GCM完全陌生,我使用下面的方法將消息發送到GCM服務器。如何從以下上下文中的響應中獲取規範ID?

public string SendMessage(string RegistrationID, string Message, string AuthString) 
    {    
     //-- Create C2DM Web Request Object --// 
     HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.clients.google.com/c2dm/send"); 
     Request.Method = "POST"; 
     Request.KeepAlive = false; 

     //-- Create Query String --// 
     NameValueCollection postFieldNameValue = new NameValueCollection(); 
     postFieldNameValue.Add("registration_id", RegistrationID); 
     postFieldNameValue.Add("collapse_key", "1"); 
     postFieldNameValue.Add("delay_while_idle", "0"); 
     // postFieldNameValue.Add("data.message", Message); 
     postFieldNameValue.Add("data.payload", Message);   
     string postData = GetPostStringFrom(postFieldNameValue); 
     byte[] byteArray = Encoding.UTF8.GetBytes(postData); 


     Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; 
     Request.ContentLength = byteArray.Length; 

     Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString); 

     //-- Delegate Modeling to Validate Server Certificate --// 
     ServicePointManager.ServerCertificateValidationCallback += delegate(
        object 
        sender, 
        System.Security.Cryptography.X509Certificates.X509Certificate 
        pCertificate, 
        System.Security.Cryptography.X509Certificates.X509Chain pChain, 
        System.Net.Security.SslPolicyErrors pSSLPolicyErrors) 
     { 
      return true; 
     }; 

     //-- Create Stream to Write Byte Array --// 
     Stream dataStream = Request.GetRequestStream(); 
     dataStream.Write(byteArray, 0, byteArray.Length); 
     dataStream.Close(); 

     //-- Post a Message --// 
     WebResponse Response = Request.GetResponse(); 
     HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode; 
     if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden)) 
     {     
      return "Unauthorized - need new token"; 

     } 
     else if (!ResponseCode.Equals(HttpStatusCode.OK)) 
     { 
      return "Response from web service isn't OK"; 
      //Console.WriteLine("Response from web service not OK :"); 
      //Console.WriteLine(((HttpWebResponse)Response).StatusDescription); 
     } 

     StreamReader Reader = new StreamReader(Response.GetResponseStream()); 
     string responseLine = Reader.ReadLine(); 

     Reader.Close(); 

     return responseLine; 
    } 

我需要在這種情況下處理規範ID。我看到了可以在Java中使用的下面的代碼片段。

if (result.getMessageId() != null) { 
String canonicalRegId = result.getCanonicalRegistrationId(); 
if (canonicalRegId != null) { 
    // same device has more than on registration ID: update database 
} 
} else { 
String error = result.getErrorCodeName(); 
if (error.equals(Constants.ERROR_NOT_REGISTERED)) { 
    // application has been removed from device - unregister database 
} 
} 

但是我怎樣才能在C#中實現相同?它沒有getCanonicalIds方法,因爲它獲得了標準的Web響應。我如何找到規範ID並將它們從桌面上移除?請指教。

回答

0

規範標識是已經在不同標識下注冊的設備的標識。當你沒有這樣的ID時,canonical_ids元素會給你0.但是如果它有一個值,那麼你在響應中的canonical_ids元素將顯示計數。在你的迴應中,這些ID將被標示爲「registration_id」。這些將按請求發送的順序進行。因此,如果響應字符串的第3個和第4個元素的值爲「registration_ids」,則意味着您在請求中發送的第3個和第4個元素ID不是正確的。用響應中的「registration_ids」中提供的ID替換它們。下面是從C#代碼中獲取這些索引和ID的代碼。

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<String> ids = new List<String>(); 
     String json ="{\"multicast_id\": \"xxxxx\",\"success\": 7,\"failure\": 0,\"canonical_ids\": 2,\"results\": [{\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}, {\"registration_id\": \"456\",\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}, {\"registration_id\": \"123\",\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}]}"; 
     RootObject decryptedMessage = new JavaScriptSerializer().Deserialize<RootObject>(json); 
     int position = 0; 
     Dictionary<int, String> canonicalIdsAndIndexes = new Dictionary<int, string>(); 
     foreach (var item in decryptedMessage.results) 
     { 
      if (item.registration_id != null) 
      { 
       canonicalIdsAndIndexes.Add(position, item.registration_id); 
       Console.WriteLine("message id: {0}, registrationid: {1}", item.message_id, item.registration_id); 
      } 
      position++; 

     } 
     Console.ReadLine(); 
    } 
} 

public class Result 
{ 
    public string message_id { get; set; } 
    public string registration_id { get; set; } 
} 

public class RootObject 
{ 
    public string multicast_id { get; set; } 
    public int success { get; set; } 
    public int failure { get; set; } 
    public int canonical_ids { get; set; } 
    public List<Result> results { get; set; } 
}