如何修复400 Bad Request错误?

时间:2012-04-12 20:37:27

标签: c#

我收到远程服务器在尝试运行我的代码时返回错误:(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 EDIT

更改为:

{ \"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();

3 个答案:

答案 0 :(得分:4)

你能试试string postData = "[{ \"username\": \"testname\" },{ \"password\": \"testpass\" }]";

吗?

这样你就发送了一个包含2个对象的数组

修改:也许你真正想要发送的只是一个有2个属性的对象,那么它就是string postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }"

答案 1 :(得分:1)

postData不是有效的Json对象

{ "username": "testname" },{ "password": "testpass" }

尝试使用Json.NetJavaScriptSerializerDataContractJsonSerializer等Json解析器,而不是手动形成

答案 2 :(得分:0)

看起来它可能来自您发布的JSON,因为它无效,请参阅下面您发送的内容但是有效格式:

{
    "username": "testname",
    "password": "testpass"
}