【发布时间】:2012-04-12 20:37:27
【问题描述】:
我收到一个远程服务器在尝试运行我的代码时返回错误:(400) Bad Request 错误。任何帮助,将不胜感激。谢谢。
// 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! -
WebClient 是个好主意。但还要注意,400 请求通常表示服务器不理解您的请求。错误的有效负载可能是罪魁祸首,尤其是因为您的 JSON 似乎不正确。
标签: c#