How to fix 400 Bad Request error?

I get The remote server returned an error: (400) Error Error while trying to run my code. Any help would be greatly appreciated. Thank.

    // 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

Changed to:

{ \"username\": \"jeff\", \"password\": \"welcome\" }

But still not working.

EDIT

Here is what I found that works:

       // 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
source share
3 answers

can try string postData = "[{ \"username\": \"testname\" },{ \"password\": \"testpass\" }]";

So you send an array of 2 objects

Change . It is also possible what you really want to send is just an object with two properties, then it will bestring postData = "{ \"username\": \"testname\", \"password\": \"testpass\" }"

+4
source

postData is not a valid Json object

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

Json, Json.Net, JavaScriptSerializer DataContractJsonSerializer

+1

It looks like this could come from the JSON that you are posting as it is invalid, see below what you submit, but in a valid form:

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

All Articles