5

我收到远程服务器返回错误:(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();
4

3 回答 3

3

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

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

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

于 2012-04-12T20:40:32.073 回答
0

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

{
    "username": "testname",
    "password": "testpass"
}
于 2012-04-12T20:41:04.503 回答
0

postData 不是有效的 Json 对象

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

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

于 2012-04-12T20:42:47.137 回答