我已经使用oAuth2从google api获得了用户访问令牌。现在我想使用这个令牌来获取用户事件/日历。我尝试过以下代码,但它不起作用。
这里有人能帮我吗。感谢
var urlBuilder = new System.Text.StringBuilder();
urlBuilder.Append("https://");
urlBuilder.Append("www.googleapis.com");
urlBuilder.Append("/calendar/v3/users/me/calendarList");
urlBuilder.Append("?minAccessRole=reader");
var httpWebRequest = HttpWebRequest.Create(urlBuilder.ToString()) as HttpWebRequest;
httpWebRequest.CookieContainer = new CookieContainer();
httpWebRequest.Headers["Authorization"] string.Format("Bearer {0}", data.access_token);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream eventResponseStream = response.GetResponseStream();
StreamReader eventResponseStreamReader = new StreamReader(responseStream);
string eventsStr = eventResponseStreamReader.ReadToEnd();
我已经找到了使用Google.Apis.Calendar.v3
的解决方案,我将其发布在这里,这样可以帮助其他人。以下是当您拥有用户的刷新令牌时获取事件列表的代码:
首先使用刷新令牌获取新的访问令牌:
string postString = "client_id=yourclientid";
postString += "&client_secret=youclientsecret&refresh_token=userrefreshtoken";
postString += "&grant_type=refresh_token";
string url = "https://www.googleapis.com/oauth2/v4/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(postString);
Stream os = null;
request.ContentLength = bytes.Length;
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
GoogleToken token = new GoogleToken();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
string result = responseStreamReader.ReadToEnd();
JavaScriptSerializer serializer = new JavaScriptSerializer();
token = serializer.Deserialize<GoogleToken>(result);
然后使用令牌和刷新令牌来创建凭据。
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = yourclientid,
ClientSecret = yourclientsecret
},
Scopes = new[] { CalendarService.Scope.Calendar }
});
var credential = new UserCredential(flow, Environment.UserName, new TokenResponse
{
AccessToken = token.access_token,
RefreshToken = userrefreshtoke
});
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "application name",
});
var list = service.CalendarList.List().Execute().Items;
foreach (var c in list)
{
var events = service.Events.List(c.Id).Execute().Items.Where(i => i.Start.DateTime >= DateTime.Now).ToList();
foreach (var e in events)
{
}
}
GoogleToken类:
public class GoogleToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public string expires_in { get; set; }
}
根据Google提供的.NET Quickstart示例,您将需要下载client_secret.json,这是身份验证过程的一部分。在链接中查看整个过程。
以下是.NET中feching事件的片段:
// List events.
Events events = request.Execute();
Console.WriteLine("Upcoming events:");
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0} ({1})", eventItem.Summary, when);
}
}
else
{
Console.WriteLine("No upcoming events found.");
}
Console.Read();
您也可以在这里阅读更多与oAuth相关的.NET指南。
有关检索日历列表和事件的更多信息,请阅读本指南。