0

我正在使用 GoogleApi。我想使用 Google api 获取 accesstoken 作为响应。当我发送 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());
            }
        }
    }
4

1 回答 1

1

这就是问题:

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

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

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

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

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

于 2013-10-17T13:26:26.603 回答