//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.
using (Stream dataStream = request.GetRequestStream())
{
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
WebResponse response = request.GetResponse();
//Error "The remote server returned an error: (400) Bad Request"
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (var reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
response.Close();
}
}
答案 0 :(得分:10)
我遇到了类似的问题。
当调用GetResponse()抛出异常时,它是一个WebException。像这样投射它,然后检查响应流。是的,内容长度为-1,但忽略它。
catch (Exception ex)
{
//byte[] buffer = new byte[999999];
WebException wex = (WebException)ex;
var s = wex.Response.GetResponseStream();
string ss = "";
int lastNum = 0;
do
{
lastNum = s.ReadByte();
ss += (char)lastNum;
} while (lastNum != -1);
s.Close();
s = null;
ErrorHasOccurred(new Exception("An error has occurred sending the notification to Urban Airship. Please see the InnerException for details. Please note that, for sending messages, the master password is required (instead of the regular password). ERROR: " + ss, ex));
}
然后只是断点,我有ErrorHasOccurred,并读取ss
变量的内容。 会告诉您Urban Airship返回的实际错误。
答案 1 :(得分:2)
你的问题是什么?服务器说你的请求很糟糕。如果您不确定实际发送到服务器的是什么,请使用Fiddler,然后修复您的请求。否则,请修复服务器代码。
无论哪种方式,如果没有一些澄清,这是“不是真正的问题”的饲料。
答案 2 :(得分:0)
这是一个有效的问题......
首先。不使用硬编码来构建json字符串,请使用JavaScriptSerializer
var json = new JavaScriptSerializer().Serialize(yourObject);
二。对于单个参数,请使用 ... BodyStyle = WebMessageBodyStyle.Bare, ... 绝对的 BodyStyle = WebMessageBodyStyle.WrappedRequest,
(我花了几个小时遇到类似的问题)