我收到遠程服務器在嘗試運行我的代碼時返回錯誤:(400)錯誤的請求錯誤。任何幫助,將不勝感激。謝謝。如何解決400錯誤請求錯誤?
// Open request and set post data
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login");
request.Method = "POST";
request.ContentType = "application/json; charset:utf-8";
string postData = "{ \"username\": \"testname\" },{ \"password\": \"testpass\" }";
// Write postData to request url
using (Stream s = request.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(postData);
}
// Get response and read it
using (Stream s = request.GetResponse().GetResponseStream()) // error happens here
{
using (StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
}
}
JSON編輯
更改爲:
{ \"username\": \"jeff\", \"password\": \"welcome\" }
但仍然沒有工作。
編輯
這是我發現的工作原理:
// Open request and set post data
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("myurl.com/restservice/Login");
request.Method = "POST";
request.ContentType = "application/json";
string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }";
// Set postData to byte type and set content length
byte[] postBytes = System.Text.UTF8Encoding.UTF8.GetBytes(postData);
request.ContentLength = postBytes.Length;
// Write postBytes to request stream
Stream s = request.GetRequestStream();
s.Write(postBytes, 0, postBytes.Length);
s.Close();
// Get the reponse
WebResponse response = request.GetResponse();
// Status for debugging
string ResponseStatus = (((HttpWebResponse)response).StatusDescription);
// Get the content from server and read it from the stream
s = response.GetResponseStream();
StreamReader reader = new StreamReader(s);
string responseFromServer = reader.ReadToEnd();
// Clean up and close
reader.Close();
s.Close();
response.Close();
爲什麼你在使用Streams?請改用['WebClient'](http://msdn.microsoft.com/zh-cn/library/system.net.webclient.aspx)! – qJake 2012-04-12 20:40:31
WebClient是一個好主意。但是請注意,400請求通常表示服務器不理解您的請求。壞的負載是可能的罪魁禍首,尤其是因爲你似乎有不正確的JSON。 – yamen 2012-04-12 20:43:45