Anurag Jain
Anurag Jain

Reputation: 1389

Json POST request to the server but server respond (400) Bad Request

I want to use google api for creation of gmail user account. I am sending JSON request to server for getting authorization code but I got these error in httpwebresponse :-

Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request

    var request = (HttpWebRequest)WebRequest.Create(@"https://accounts.google.com/o/oauth2/auth");
    request.Method = "POST";
    request.ContentType = "text/json";
    request.KeepAlive = false;

    //request.ContentLength = 0;

    using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string json = "{\"scope\":\"https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile\"," + "\"state\":\"%2Fprofile\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"response_type\":\"code\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"}";

        streamWriter.Write(json);
        // streamWriter.Flush();
        //streamWriter.Close();
    }
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            StreamReader responsereader = new StreamReader(response.GetResponseStream());

            var responsedata = responsereader.ReadToEnd();
            //Session["responseinfo"] = responsereader;

            //testdiv.InnerHtml = responsedata;
        }

}

Upvotes: 1

Views: 8595

Answers (1)

Vladimir Gondarev
Vladimir Gondarev

Reputation: 1243

As soon as you get an exception, you have to read the actual responce from server there should be something helpfull. Like an error description or extended status code...

For Instance:

try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

         ... your code goes here....

}
catch (WebException ex)
        {
        using (WebResponse response = ex.Response)
        {
            var httpResponse = (HttpWebResponse)response;

            using (Stream data = response.GetResponseStream())
            {
                StreamReader sr = new StreamReader(data);
                throw new Exception(sr.ReadToEnd());
            }
        }
    }

Upvotes: 12

Related Questions