在C#上使用Content Type应用程序Json发送Http请求

时间:2013-07-11 16:17:27

标签: c# asp.net httpwebrequest amazon-device-messaging

尝试通过C#发送内容类型application / json的HTTP Get请求。但我没有找到如何创建此请求。 我的HTTP请求是这样的:

POST /messaging/registrations/(REGISTRATION_ID_FOR_DESTINATION_APP_INSTANCE)/messages HTTP/1.1
Host: api.amazon.com
Authorization: Bearer (MY_ACCESS_TOKEN)
Content-Type: application/json
X-Amzn-Type-Version: com.amazon.device.messaging.ADMMessage@1.0
Accept: application/json
X-Amzn-Accept-Type: com.amazon.device.messaging.ADMSendResult@1.0

{
    "data":{"key1":"value1","key2":"value2"},
    "consolidationKey":"Some Key",
    "expiresAfter":86400
}

有人可以帮助我。 为所有人思考。

1 个答案:

答案 0 :(得分:1)

假设您有一个这样的类来表示有效负载,

class Payload
{
        public Dictionary<string, string> data { get; set; }
        public string consolidationKey { get; set;}
        public long expiresAfter { get; set; }
}

你可以像这样使用HttpClient

string url = "http://api.amazon.com/messaging/registrations/1234/messages";
var client = new HttpClient();

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                                              "Bearer", "token");
client.DefaultRequestHeaders.Accept.Add(
              new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-Amzn-Type-Version",
                                   "com.amazon.device.messaging.ADMMessage@1.0");
client.DefaultRequestHeaders.Add("X-Amzn-Accept-Type",
                                "com.amazon.device.messaging.ADMSendResult@1.0");

var kvp = new Dictionary<string, string>();
kvp.Add("key1", "value1");
kvp.Add("key2", "value2");

var payload = new Payload()
{
    consolidationKey = "Some Key", expiresAfter = 86400, data = kvp
};

var result = client.PostAsJsonAsync<Payload>(url, payload).Result;