HttpWebRequest方法GET / POST无法正常工作?

时间:2013-10-17 13:24:45

标签: c# json post get httpwebrequest

我正在使用GoogleApi。我希望使用Google api获取accessstoken响应。当我发送httpwebrequest以获取访问令牌时

当我使用时: - request.Method =“POST”

例外: - 此URL不支持HTTP方法POST

当我使用时: - request.Method =“GET”

异常: - System.Net.ProtocolViolationException:无法使用此动词类型发送内容正文

实际请求可能如下所示:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code

成功的响应作为JSON数组返回,类似于以下内容:

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"

}

我的代码是: -

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

    // request.Headers[HttpRequestHeader.Authorization] = "";
    //request.ContentLength = 0;

    using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        string json = "{\"code\":\"4/M1IIC8htCuvYORuVJK16oadDb3Gd.cigIKgaPjvUYXE-sT2ZLcbSrckCLgwI\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"," + "\"client_secret\":\"MXjKvevD_cKp5eQWZ1RFXfdo\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"grant_type\":\"authorization_code\"}";

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

            var responsedata = responsereader.ReadToEnd();
            //Session["responseinfo"] = responsereader;     
        }
    }
    catch (WebException ex)
    {
        using (WebResponse response = ex.Response)
        {
            var httpResponse = (HttpWebResponse)response;

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

1 个答案:

答案 0 :(得分:1)

这是问题所在:

var request = (HttpWebRequest)WebRequest.Create(@"https://accounts.google.com");

这不是您最初显示的网址。那只是域根。你需要:

var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");

我删除了@,因为你的字符串不包含任何换行符或反斜杠,因此使用逐字字符串文字没有任何好处。

(另外,我希望Google客户端API能够涵盖这一点 - 不是吗?)