HttpWebRequest asp.net returning error 400

0

I'm doing a query on a api to get a token access, using Postman , the options Body and Raw , passing the access data on the body, everything works fine, more in my example I have the error:

  

An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code   Additional information: The remote server returned an error: (400) Request Incorrect.

public string ConsultarUsuario(string url)
{

    var request = (HttpWebRequest)WebRequest.Create(url);
    var postData = "{ username:sistema, password:senha }";
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "raw";
    //  request.ContentType = "application/json";
    // request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream())
    {
          stream.Write(data, 0, data.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            return responseString;
}
    
asked by anonymous 04.12.2017 / 03:34

1 answer

1

The way to do it would be:

        public string ConsultaUsuario(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = new JavaScriptSerializer().Serialize(new
                {
                    username = "login",
                    password = "senha"
                });

                streamWriter.Write(json);
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                return streamReader.ReadToEnd();
            }

        }
    
06.12.2017 / 01:50