GoogleCalendarAPI-BadRequest(400)AttempttoExchangeAccessTokenCode在获得谷歌访问用户日历的授权码后,我'现在试图用访问令牌替换它。根据自己的文档:实际请求可能如下所示:POST/o/oauth2/tokenHTTP/1.1Host:accounts.google.comContent-Type:application/x-www-form-urlencodedcode=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&client_id=8819981768.apps.googleusercontent.com&client_secret={client_secret}&redirect_uri=https://oauth2-login-demo.appspot.com/code&grant_type=authorization_code我尝试访问的方式如下(C#):stringurl=“https://accounts.google.com/o/oauth2/token”;WebRequest请求=HttpWebRequest.Create(url);request.Method="POST";request.ContentType="application/x-www-form-urlencoded";stringbody="code=&rn"+"client_id=&rn"+"client_secret=&rn"+"redirect_uri=http://localhost:4300rn"+"grant_type=authorization_code&rn";byte[]bodyBytes=Encoding.ASCII.GetBytes(正文);request.ContentLength=bodyBytes.Length;StreambodyStream=request.GetRequestStream();bodyStream.Write(bodyBytes,0,bodyBytes.Length);bodyStream.Close();尝试{request.GetResponse();'http://localhost:4300'与我在原始请求中的完全相同(它之所以有效,是因为我通过监听该端口作为Web服务器获得了代码),但我也尝试了'http://localhost'以防万一我尝试了一些建议,例如将Proxy设置为null(无更改)和更改Accept(不允许将该标头添加到Web请求)。在每种情况下,我都会收到HTTP400-BadRequest(try/catchfires,有例外)。在/token之后添加一个斜杠(我会尝试任何事情!)会导致500内部服务器错误,因此两者都不会。知道我做错了什么吗?您需要在正文中添加新行rn吗?这段代码对我有用...以上是C#教程:GoogleCalendarAPI-BadRequest(400)Attempttoexchangeaccesstoken代码分享全部内容,如果它对你有用并且需要了解更多关于C#教程,我希望大家多多关注——varreq0=WebRequest.Create("https://accounts.google.com/o/oauth2/token");req0.Method="POST";stringpostData=string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code,//我得到的代码"2xxx61.apps.googleusercontent.com","XJxxxFy","http://localhost:1599/home/oauth2callback");//我的返回URIbyte[]byteArray=Encoding.UTF8.GetBytes(postData);req0.ContentType="application/x-www-form-urlencoded";req0.ContentLength=byteArray.Length;使用(StreamdataStream=req0.GetRequestStream()){dataStream.Write(byteArray,0,byteArray.Length);数据流.关闭();}try{使用(WebResponseresponse=req0.GetResponse()){使用(vardataStream=response.GetResponseStream()){使用(StreamReaderreader=newStreamReader(dataStream)){stringresponseFromServer=reader.ReadToEnd();varser=newJavaScriptSerializer();accessToken=ser.DeserializeObject(responseFromServer);}}}}catch(WebExceptionwex){varx=wex;(Exceptionex){varx=ex;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
