我正在尝试访问 Google API v3 日历列表,但即使我有用户的有效 AccessToken,我也会不断收到 401/404 响应。
(我完成了Web Server Applications 的 OAuth2 协议,并获得了https://www.googleapis.com/auth/calendar权限)
很难找到好的文档,谷歌网站本身不是很有帮助,搜索充满了旧的 v2 信息或使用 SDK。通常我可以将 python 回复翻译成 c#,但在这种情况下,即使这样也对我没有帮助。
所以我把头发拉了出来,但我可能在这里忘记了一些非常简单的东西,比如缺少参数或类似的东西,所以如果有人能快速查看这段代码并告诉我我做错了什么,将不胜感激.
var applicationKey = moduleModel.Application.Key;
var userID = moduleModel.User.UserID;
var accessToken = moduleModel.User.AccessToken.Token;
// It doesn't seem to make any difference whether I use the querystring
// parameter or the request header to specify the access_token
var sendAccessTokenAsHeader =
!(Request.QueryString["SendAccessTokenAsHeader"] == "0");
// I tried navigating to a specific user but it results in a 404 Not Found
var requestSpecificUserID =
Request.QueryString["RequestSpecificUserID"] == "1";
// Including or omitting my API_KEY doesn't seem to make any difference
var sendApplicationKey =
!(Request.QueryString["SendApplicationKey"] == "0");
var urlBuilder = new System.Text.StringBuilder();
urlBuilder.Append("https://");
urlBuilder.Append("www.googleapis.com");
if (requestSpecificUserID)
{
urlBuilder.Append
(string.Format("/calendar/v3/users/{0}/calendarList", userID));
}
else
{
urlBuilder.Append
("/calendar/v3/users/me/calendarList");
}
var parameterJoiner = "?";
if (sendApplicationKey)
{
urlBuilder.Append
(
string.Format
(
"{0}{1}={2}",
parameterJoiner,
"key",
HttpUtility.UrlEncode(applicationKey)
)
);
parameterJoiner = "&";
}
if (!sendAccessTokenAsHeader)
{
urlBuilder.Append
(
string.Format
(
"{0}{1}={2}",
parameterJoiner,
"access_token",
HttpUtility.UrlEncode(accessToken)
)
);
parameterJoiner = "&";
}
var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString())
as HttpWebRequest;
httpWebRequest.CookieContainer = new CookieContainer();
if (sendAccessTokenAsHeader)
{
httpWebRequest.Headers["Authorization"] = string.Format
(
"Bearer {0}",
accessToken
);
}
// GetSafeResponse is just an extension method to catch the WebException
// when the HttpStatusCode != OK
var response = httpWebRequest.GetSafeResponse();
// returns 401 (requestSpecificUserID = false)
// or 404 (requestSpecificUserID = true)
var responseText = response.GetResponseText();
return responseText;
先感谢您!