本文介绍了如何使用访问令牌和刷新令牌从Google API访问用户日历列表和事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用oAuth2从Google api获取用户访问令牌.现在,我想使用此令牌获取用户事件/日历.我已经尝试过以下代码,但无法正常工作.

I already have obtained users access token from google api using oAuth2. Now i want to use this token to get user events/calendars. I have tried following code but it is not working.

这里有人可以帮助我吗?谢谢

Can anyone here help me with this please.Thanks

    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的解决方案,我将其发布在这里,所以可能会对其他人有所帮助.以下是当您具有用户的刷新令牌时获取事件列表的代码:

I have found solution using Google.Apis.Calendar.v3, i am posting it here so may help someone else. Following is the code to get the events list when you have refresh token of a user:

首先使用刷新令牌获取新的访问令牌:

First get new access token using the refresh token:

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);

然后使用令牌和刷新令牌创建凭据.

Then use the toke and refresh token to create credentials.

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类:

GoogleToken class:

 public class GoogleToken
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string expires_in { get; set; }
    }

这篇关于如何使用访问令牌和刷新令牌从Google API访问用户日历列表和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 00:24
查看更多