我创建了一个 Web 应用程序,旨在让人们有机会与我安排约会,我使用业务逻辑来验证时间是否有效。我将所有约会都保留在 Google 日历上。于是我就去 Google API Console 创建了 Web Application Project。我得到了我的 client_id 和秘密。我能够很好地检索访问令牌。我什至有刷新令牌和构建逻辑来自动刷新访问令牌并且工作正常。我使用这个令牌来检索日历事件列表并且工作正常。然后,我使用令牌插入新的日历事件,但出现错误。首先是代码:
public CalendarEvent InsertCalendarEvent(CalendarEditArgs args)
{
string url = "https://www.googleapis.com/calendar/v3/calendars/" + HttpUtility.UrlEncode(args.CalendarId) + "/events?&key=" + args.APIKey;
Web.SetUpPost(url, null, true, JsonConvert.SerializeObject(args.Event), null, null, new { Name = "Authorization", Value = "Bearer " + args.AccessToken }, new { Name = "X-JavaScript-User-Agent", Value = "Easy SPS" });
string response = null;
try
{
response = Web.GetResponse();
return JsonConvert.DeserializeObject<CalendarEvent>(response);
}
catch(WebException e)
{
response = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
throw new Exception(response, e);
}
}
public void SetUpPost(string url, string parameters, bool json, string body, string clientKey, string clientSecret, params object[] data)
{
if (body != null && parameters != null)
throw new InvalidOperationException("You cannot submit a request body and parameters at the same time.");
request = WebRequest.Create(url) as HttpWebRequest;
if (!json)
{
request.ContentType = "application/x-www-form-urlencoded";
}
else
{
request.ContentType = "application/json";
}
request.Headers.Add("Accept-Charset", "utf-8");
request.Method = "POST";
request.Referer = "https://www.easy-sps.com";
request.KeepAlive = true;
byte[] bytes = null;
if (body != null || parameters != null)
{
bytes = System.Text.Encoding.ASCII.GetBytes(body == null ? parameters : body);
request.ContentLength = bytes.Length;
System.IO.Stream os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
}
else
{
request.ContentLength = 0;
}
if (data != null)
{
foreach (var dataObject in data)
{
PropertyInfo prop = dataObject.GetType().GetProperties()[0];
PropertyInfo prop2 = dataObject.GetType().GetProperties()[1];
request.Headers.Add(prop.GetValue(dataObject, null).ToString(), prop2.GetValue(dataObject, null).ToString());
}
}
}
}
The error I get:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
几个注意事项我实际上并没有使用客户端密钥和客户端密钥,因为它们用于获取令牌而不是使用它。要检索令牌,我确实必须通过离线访问登录到谷歌(我知道这有效,因为谷歌表示即使我不在线,我也会授予对日历的访问权限)。我去了谷歌游乐场,在那里我可以让它工作,但不是在这里。我试图找出我发布的内容和发布的内容之间的区别,但我找不到任何东西。任何帮助将不胜感激。一个多星期以来一直坚持零进度,而且我们知道谷歌不直接支持它的开发人员,只是通过它的论坛,我根本无法在那些论坛中找到我还没有尝试过的东西的情况。