繁体   English   中英

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

[英]HttpWebRequest method GET/POST not working?

我正在使用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());
            }
        }
    }

这就是问题:

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

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

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

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

(此外,我希望Google Client API可以涵盖此内容-是吗?)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM