JSON POST请求服务器,但服务器响应(400)错误请求

时间:2013-10-17 08:23:30

标签: c# json post httpwebrequest httpwebresponse

我想使用google api创建gmail用户帐户。我正在向服务器发送JSON请求以获取授权代码,但我在httpwebresponse中收到了这些错误: -

异常详细信息:System.Net.WebException:远程服务器返回错误:(400)错误请求

    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;
        }

}

1 个答案:

答案 0 :(得分:11)

一旦你得到一个例外,你必须从服务器读取实际的响应,应该有一些有用的东西。像错误描述或扩展状态代码......

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());
            }
        }
    }