2010-03-06 142 views

回答

16

基本上。 ..

using System; 
using System.IO; 
using System.Net; 
using System.Text; 

namespace Examples.System.Net 
{ 
    public class WebRequestPostExample 
    { 
     public static void Main() 
     { 
      // Create a request using a URL that can receive a post. 
      WebRequest request = WebRequest.Create ("https://go.urbanairship.com/api/push/"); 
      // Set the Method property of the request to POST. 
      request.Method = "POST"; 

      // Create POST data and convert it to a byte array. 

爆发了多行,所以你可以看它

  string postData = "{ 
    "device_tokens": [ 
     "some device token", 
     "another device token" 
    ], 
    "aliases": [ 
     "user1", 
     "user2" 
    ], 
    "tags": [ 
     "tag1", 
     "tag2" 
    ], 
    "schedule_for": [ 
     "2010-07-27 22:48:00", 
     "2010-07-28 22:48:00" 
    ], 
    "exclude_tokens": [ 
     "device token you want to skip", 
     "another device token you want to skip" 
    ], 
    "aps": { 
     "badge": 10, 
     "alert": "Hello from Urban Airship!", 
     "sound": "cat.caf" 
    } 
}"; 

然后

  byte[] byteArray = Encoding.UTF8.GetBytes (postData); 
      // Set the ContentType property of the WebRequest. 
      request.ContentType = "application/json"; 
      // Set the ContentLength property of the WebRequest. 
      request.ContentLength = byteArray.Length; 

      //Do a http basic authentication somehow 
      string username = "<application key from urban airship>"; 
      string password = "<master secret from urban airship>"; 
      string usernamePassword = username + ":" + password; 
      CredentialCache mycache = new CredentialCache(); 
      mycache.Add(new Uri("https://go.urbanairship.com/api/push/"), "Basic", new NetworkCredential(username, password)); 
      request.Credentials = mycache; 
      request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword))); 

      // Get the request stream. 
      Stream dataStream = request.GetRequestStream(); 
      // Write the data to the request stream. 
      dataStream.Write (byteArray, 0, byteArray.Length); 
      // Close the Stream object. 
      dataStream.Close(); 
      // Get the response. 
      WebResponse response = request.GetResponse(); 
      // Display the status. 
      Console.WriteLine (((HttpWebResponse)response).StatusDescription); 
      // Get the stream containing content returned by the server. 
      dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader (dataStream); 
      // Read the content. 
      string responseFromServer = reader.ReadToEnd(); 
      // Display the content. 
      Console.WriteLine (responseFromServer); 
      // Clean up the streams. 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 
     } 
    } 
} 

api docsmsdnhere for more on https

+2

很好的答案,SLF! – Jann 2010-03-20 01:06:25

11

接受的答案是不行的,需要更改以下行:

request.ContentType = "application/x-www-form-urlencoded"; 

request.ContentType = "application/json"; 
如下图所示

完整的工作代码:

using System; 
using System.IO; 
using System.Net; 
using System.Text; 

namespace UrbanAirship_Tes_1 
{ 
    class Program 
    { 
     public static void Main() 
     { 

      // Create a request using a URL that can receive a post. 
      WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/"); 
      request.Credentials = new NetworkCredential("pvYMExk3QIO7p2YUs6BBkg", "rO3DsucETRadbbfxHkd6qw"); 
      // Set the Method property of the request to POST. 
      request.Method = "POST"; 
      // Create POST data and convert it to a byte array. 
      //WRITE JSON DATA TO VARIABLE D 
      string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"6334c016fc643baa340eca25bc661d15055a07b475e9a6108f3f644b15dd05ac\"]}"; 
      byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
      // Set the ContentType property of the WebRequest. 
      request.ContentType = "application/json"; 
      // Set the ContentLength property of the WebRequest. 
      request.ContentLength = byteArray.Length; 
      // Get the request stream. 
      Stream dataStream = request.GetRequestStream(); 
      // Write the data to the request stream. 
      dataStream.Write(byteArray, 0, byteArray.Length); 
      // Close the Stream object. 
      dataStream.Close(); 
      // Get the response. 
      WebResponse response = request.GetResponse(); 
      // Display the status. 
      //   Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
      // Get the stream containing content returned by the server. 
      dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 
      // Read the content. 
      string responseFromServer = reader.ReadToEnd(); 
      // Display the content. 
      Console.WriteLine(responseFromServer); 
      // Clean up the streams. 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 
     } 
    } 
} 
+0

哇答案奏效。看看我是新来的,想要相同的,想发送数据到iPhone,Android和黑莓的应用程序。我是一个在sebservice上工作的Web开发人员,他将生成推送消息给客户端应用程序。 – LojiSmith 2013-06-20 08:01:02

+0

这个答案与以下错误一起工作。从你的代码 – LojiSmith 2013-06-20 08:01:26

+1

我刚刚更改了网络线的用户名和密码。 {System.Net.WebException:远程服务器返回一个错误:(401)未经授权。 at System.Net.HttpWebRequest.GetResponse() at ConsoleApplication1.Program.Main(String [] args)in c:\ Users \ Window8 \ Downloads \ urban-airship-windows-latest \ urban-airship-windows-1_0_1_0 \ ConsoleApplication1 \ Program.cs:第38行} – LojiSmith 2013-06-20 08:02:47

1
public class PushNotificationHelper 
{ 
    private readonly ILog log4netEngine; 

    private string UrbanAirshipApplicationKey { get; set; } 
    private string UrbanAirshipApplicationSecret { get; set; } 
    private string UrbanAirshipApplicationMasterSecret { get; set; } 

    public PushNotificationHelper(string UrbanAirshipApplicationKey, string UrbanAirshipApplicationSecret, string UrbanAirshipApplicationMasterSecret) 
    { 
     log4netEngine = LogManager.GetLogger(typeof(PushNotificationHelper).Name); 

     this.UrbanAirshipApplicationKey = UrbanAirshipApplicationKey; 
     this.UrbanAirshipApplicationSecret = UrbanAirshipApplicationSecret; 
     this.UrbanAirshipApplicationMasterSecret = UrbanAirshipApplicationMasterSecret; 
    } 


    public void PushNotification2iPhones(string alertText, string[] apids, string extra) 
    { 
     if (!string.IsNullOrEmpty(alertText) && apids.Length > 0) 
     { 
      iPhonePushNotification pushNotification = new iPhonePushNotification 
      { 
       MessageBody = new iPhonePushNotificationMessageBody 
       { 
        Alert = alertText 
       }, 
       Extra = extra, 
       APIDs = apids 
      }; 
      string jsonMessageRequest = pushNotification.ToJsonString(); 
      try 
      { 
       SendMessageToUrbanAirship(jsonMessageRequest); 
       log4netEngine.InfoFormat("Push Notification Success , iPhoneDevice:{0}, message:{1},extra:{2}", string.Join(",", apids), alertText, extra); 
      } 
      catch (Exception ex) 
      { 
       log4netEngine.InfoFormat("Push Notification Error:{0}, iPhoneDevice:{1}, message:{2},extra:{3}", ex.Message, string.Join(",", apids), alertText, extra); 
      } 
     } 
    } 


    public void PushNotification2Androids(string alertText, string[] apids, string extra) 
    { 
     if (!string.IsNullOrEmpty(alertText) && apids.Length > 0) 
     { 
      AndroidPushNotification pushNotification = new AndroidPushNotification 
      { 
       MessageBody = new AndroidPushNotificationMessageBody 
       { 
        Alert = alertText, 
        Extra = extra 
       }, 
       APIDs = apids 
      }; 
      string jsonMessageRequest = pushNotification.ToJsonString(); 

      try 
      { 
       SendMessageToUrbanAirship(jsonMessageRequest); 
       log4netEngine.InfoFormat("Push Notification Success , androidDevice:{0}, message:{1},extra:{2}", string.Join(",", apids), alertText, extra); 
      } 
      catch (Exception ex) 
      { 
       log4netEngine.InfoFormat("Push Notification Error:{0}, androidDevice:{1}, message:{2},extra:{3}", ex.Message, string.Join(",", apids), alertText, extra); 
      } 
     } 
    } 

    private void SendMessageToUrbanAirship(string jsonMessageRequest) 
    { 
     var uri = new Uri("https://go.urbanairship.com/api/push/"); 
     var encoding = new UTF8Encoding(); 
     var request = WebRequest.Create(uri); 
     request.Method = "POST"; 
     request.Credentials = new NetworkCredential(this.UrbanAirshipApplicationKey, this.UrbanAirshipApplicationMasterSecret); 
     request.ContentType = "application/json"; 
     request.ContentLength = encoding.GetByteCount(jsonMessageRequest); 
     using (var stream = request.GetRequestStream()) 
     { 
      stream.Write(encoding.GetBytes(jsonMessageRequest), 0, encoding.GetByteCount(jsonMessageRequest)); 
      stream.Close(); 
      var response = request.GetResponse(); 
      response.Close(); 
     } 
    } 
} 

public class NotificationToPush 
{ 
    public int ReceiverUserID { get; set; } 
    public string Message { get; set; } 
    public Dictionary<string, string> Extra { get; set; } 
} 

[DataContract(Name = "PushNotificationBody")] 
internal class PushNotification 
{ 
    public string ToJsonString() 
    { 
     var result = JsonConvert.SerializeObject(this); 
     return result; 
    } 
} 

[DataContract(Name = "iPhonePushNotification")] 
internal class iPhonePushNotification : PushNotification 
{ 
    [DataMember(Name = "aps")] 
    public iPhonePushNotificationMessageBody MessageBody { get; set; } 

    [DataMember(Name = "extra")] 
    public string Extra { get; set; } 

    [DataMember(Name = "device_tokens")] 
    public string[] APIDs { get; set; } 
} 

[DataContract(Name = "iPhonePushNotificationMessageBody")] 
internal class iPhonePushNotificationMessageBody 
{ 
    [DataMember(Name = "alert")] 
    public string Alert { get; set; } 
} 

[DataContract(Name = "AndroidPushNotification")] 
internal class AndroidPushNotification : PushNotification 
{ 
    [DataMember(Name = "android")] 
    public AndroidPushNotificationMessageBody MessageBody { get; set; } 

    [DataMember(Name = "apids")] 
    public string[] APIDs { get; set; } 
} 

[DataContract(Name = "AndroidPushNotificationMessageBody")] 
internal class AndroidPushNotificationMessageBody 
{ 
    [DataMember(Name = "alert")] 
    public string Alert { get; set; } 

    [DataMember(Name = "extra")] 
    public string Extra { get; set; } 
} 
0

下面是如何使用System.Net.Http.HttpClient异步方法来做到这一点。

var handler = new HttpClientHandler { Credentials = new NetworkCredential(urbanairshipapiKey, urbanairshipApiAppMasterSecret) }; 
var client = new HttpClient(handler); 
var added = client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/vnd.urbanairship+json; version=3;"); 

var response = await client.PostAsync(apiUrl + "/push/", new StringContent(json, Encoding.UTF8, "application/json"));