使用C#上的Content-Type应用程序Json发送Http请求
本文关键字:发送 Http 请求 Json 应用程序 上的 Content-Type 使用 | 更新日期: 2023-09-27 18:21:56
Am正在尝试通过C#发送带有Content-Type application/json的HTTPGet请求。但是我不知道如何创建这个请求。我的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
}
请有人帮我。为所有人着想。
假设您有一个这样的类来表示有效载荷,
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;