在 C# 上发送带有内容类型应用程序 Json 的 post Https 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18081401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
send post Https request with Content Type application Json on C#
提问by mouhcine
I m trying to send the following request :
我正在尝试发送以下请求:
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: [email protected]
Accept: application/json
X-Amzn-Accept-Type: [email protected]
{
"data":{"message":"value1","title":"value2"},
"consolidationKey":"Some Key",
"expiresAfter":86400
}
in order to get a response format like this:
为了获得这样的响应格式:
HTTP/1.1 200
X-Amzn-Data-md5: t5psxALRTM7WN30Q8f20tw==
X-Amzn-RequestId: e8bef3ce-242e-11e2-8484-47f4656fc00d
Content-Type: application/json
X-Amzn-Type-Version: [email protected]
Content-Length: 308
{"registrationID":(REGISTRATION_ID_FOR_DESTINATION_APP_INSTANCE)}
to do that I tried with this code :
为此,我尝试使用此代码:
private void sendNotification(String registrationID,String message,
String title,String accessToken)
{
//registrationID content (REGISTRATION_ID_FOR_DESTINATION_APP_INSTANCE) that can vary
string url = "https://api.amazon.com/messaging/registrations/"+ registrationID +"/messages";
var client = new HttpClient();
//set Request headers
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", accessToken);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-Amzn-Type-Version",
"[email protected]");
client.DefaultRequestHeaders.Add("X-Amzn-Accept-Type",
"[email protected]");
//the content of the message body
var content = new Dictionary<string, Object>();
content.Add("consolidationKey", "SyncNow");
content.Add("expiresAfter", 86400);
var data = new Dictionary<string, string>();
data.Add("message", message);
data.Add("title", title);
content.Add("data", data);
var result = client.PostAsJsonAsync<Dictionary<string, Object>>(url, content).Result;
}
As response I get StatusCode:400,ReasonPhrase:'Bad Request', I don't know why ??
作为回应,我得到 StatusCode:400,ReasonPhrase:'Bad Request',我不知道为什么?
someone can help me, please !!
有人可以帮助我,请!
For detail about result wich I got:
有关我得到的结果的详细信息:
result {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
x-amzn-RequestId: 1b943a1c-fe94-11e2-b963-71a537223b43
Vary: Accept-Encoding
Vary: User-Agent
Cneonction: close
Date: Tue, 06 Aug 2013 12:31:24 GMT
Content-Length: 34
Content-Type: application/json
}} System.Net.Http.HttpResponseMessage
result.RequestMessage {Method: POST,
RequestUri: 'https://api.amazon.com/messaging/registrations/(REGISTRATION_ID_FOR_DESTINATION_APP_INSTANCE)/messages',
Version: 1.1,
Content: System.Net.Http.ObjectContent`1[[System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],
[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],
Headers:
{
Authorization: Bearer (MY_ACCESS_TOKEN)
Accept: application/json
X-Amzn-Type-Version: [email protected]
X-Amzn-Accept-Type: [email protected]
Content-Type: application/json; charset=utf-8
Content-Length: 98
}} System.Net.Http.HttpRequestMessage
采纳答案by mouhcine
I found an other solution that work perfectly .
我找到了另一个完美的解决方案。
private void sendNotification(String registrationID,String message,String title,String accessToken)
{
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("https://api.amazon.com/messaging/registrations/" + registrationID + "/messages");
Encoding encoding = new UTF8Encoding();
string postData = "{\"data\":{\"message\":\""+message+"\",\"title\":\""+title+"\"},\"consolidationKey\":\"Some Key\",\"expiresAfter\":86400}";
byte[] data = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "POST";
httpWReq.ContentType = "application/json";//charset=UTF-8";
httpWReq.Headers.Add("X-Amzn-Type-Version",
"[email protected]");
httpWReq.Headers.Add("X-Amzn-Accept-Type",
"[email protected]");
httpWReq.Headers.Add(HttpRequestHeader.Authorization,
"Bearer " + accessToken);
httpWReq.ContentLength = data.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s=response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
String jsonresponse = "";
String temp = null;
while ((temp = reader.ReadLine()) != null)
{
jsonresponse += temp;
}
}
回答by cgotberg
Just looking at this quickly it seems like this line of code is wrong.
快速浏览一下,似乎这行代码是错误的。
var result = client.PostAsJsonAsync<Dictionary<string, Object>>(url, data).Result;
based on fact that you're saying amazon wants the post json to look like this.
基于您说亚马逊希望帖子 json 看起来像这样的事实。
{"data":{"message":"value1","title":"value2"},"consolidationKey":"Some Key","expiresAfter":86400}
It seems like you should be passing your var content to the post rather than var data. I.e.
似乎您应该将 var 内容而不是 var 数据传递给帖子。IE
var result = client.PostAsJsonAsync<Dictionary<string, Object>>(url, content).Result;

