使用java离线访问谷歌日历 [英] Offline Access to google calendar using java

查看:198
本文介绍了使用java离线访问谷歌日历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有代码将我们的应用程序日历与登录用户的Google日历同步。该代码使用的是AuthSub和CalendarService类,但它不提供使用访问令牌和刷新令牌的谷歌日历的离线访问,因为我想使用日历类来使用OAuth v3。我面临的问题是将我的旧代码合并到没有getFeed()函数的新v3 Calendar类。以下是我的应用程序中的一些代码

We have code to sync our application calendar with google calendar of logged in user. The code is using AuthSub and CalendarService class but it does not provide offline access to google calendar using access token and refresh token for that i want to use OAuth v3 using calendar class. I am facing problem to merge my old code to new v3 Calendar class which is not having getFeed() function. Here is some code from my application

if(StringUtil.isValid(request.getQueryString())) {
                onetimeUseToken = AuthSubUtil.getTokenFromReply(request.getQueryString());
            }       

            if(StringUtil.isValid(onetimeUseToken)) {           

                    String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken,null);
                    CalendarService calendarService = new CalendarService("myapp");
                    calendarService.setAuthSubToken(sessionToken, null);    
                    session.setAttribute("calendarServicesession",calendarService);
                    userIDforCalendar = (String) session.getAttribute("calendar_user_no");
                        }

                       CalendarFeed myResultsFeed1 =service.getFeed(new URL("https://www.google.com/calendar/feeds/default/allcalendars/full"),CalendarFeed.class);

            for (int i = 0; i < myResultsFeed1.getEntries().size(); i++) {
                CalendarEntry entry = myResultsFeed1.getEntries().get(i);
                           .....

}

请提供给我某种方式使用CalendarService提供离线访问,这样我就不必更改代码了。
希望快速回复。

Please provide me some way to give offline access using CalendarService so that I don't have to change my code much. Hoping for a quick reply.

谢谢 -
Dravit Gupta

Thanks- Dravit Gupta

推荐答案

Google从2012年4月20日起弃用了AuthSub。现在是时候迁移到OAuth 2.0和Google Calendar API v3了。首先从以下链接下载jar文件:

Google deprecated AuthSub from 20 April 2012. So it is time you migrated to OAuth 2.0 and Google Calendar API v3. First download the jar files from these following links:

https://google-api-client-libraries.appspot.com/download/library/calendar/v3/java

http://google-oauth-java-client.googlecode.com/files/google-oauth-java-client-1.13.1-beta.zip

从项目中删除旧日历和Authsub jar文件,并从此链接添加jar文件。

Remove the old calendar and Authsub jar files from your project and add the jar files from this link.

然后转到google api console获取您的客户端ID,客户端秘密并创建重定向uri。
并且从相同的api控制台启用google calendar api。

Then go to google api console to get your client id, client secret and create a redirect uri. And from the same api console enable google calendar api.

我给你一个示例代码,用于验证用户身份并显示他拥有的日历存储您在输出中获得的刷新令牌并将其存储,以便您可以脱机访问日历。

I am giving you a sample code that authenticates the user and shows the calendars that he has you have to store the refresh token that you get in the output and store it so that you can access the calendar offline.

以下功能用于OAuth授权。

This following function is for OAuth authorization.

 public void authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String client_id                = "xxxx";
    String redirect_uri             = "xxxxxx";
    String scope                    = "https://www.googleapis.com/auth/calendar";
    String client_secret            = "xxxxxx";
    List <String> scopes;
    HttpTransport transport         = new NetHttpTransport();
    JsonFactory jsonFactory         = new JacksonFactory();

    scopes = new LinkedList<String>();
    scopes.add(scope);
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, client_id, client_secret, scopes).build();
    GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
    url.setRedirectUri(redirect_uri);
    url.setApprovalPrompt("force");
    url.setAccessType("offline");
    String authorize_url = url.build();
    response.sendRedirect(authorize_url);
}

您必须为变量添加值 client_id client_secret redirect_uri 。所有这些值都在您的google api控制台中。

You have to add values to the variables client_id, client_secret and redirect_uri. All these values are in your google api console.

授权功能会将我转发到授权网址,该网址会为我提供访问令牌和刷新令牌。但是,访问令牌在一段时间后过期。因此,如果您需要访问令牌,则需要存储刷新令牌并使用该令牌在您访问日历api时生成它。

The authorization function forwards me to the authorize url which gives me an access token and a refresh token. However, access token expires after a time interval. So if you want the access token you need to store the refresh token and using that generate it whenever you access the calendar api.

以下函数生成访问令牌和刷新令牌并打印用户谷歌日历中的日历列表。

This following function generates access token and refresh token and prints the list of calendars in the users google calendar.

public void importCalendarList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    HttpSession session = request.getSession();
    String staffKey = (String) session.getAttribute("staffKey");
    ContactJdo staffDetails = staff.getStaffDetail(staffKey);
    String code = request.getParameter("code");
    String calendarId="";

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, client_id, client_secret, scopes).build();
    GoogleTokenResponse res = flow.newTokenRequest(code).setRedirectUri(redirect_uri).execute();
    String refreshToken = res.getRefreshToken();
    String accessToken = res.getAccessToken();

    List <CalendarListEntry>list1= getCalendars(accessToken);

    for(CalendarListEntry temp:list1) {
        System.out.println(temp.getId());
    }}

如果查看上面的函数,它会同时生成访问和刷新令牌。如果要再次生成访问令牌,请使用以下函数:

If you look at the above function, it generates both access and refresh tokens. If you want to generate access token again use this function:

public static String getAccessToken(String refreshToken, String client_id, String client_secret) throws IOException {
    HttpTransport transport         = new NetHttpTransport();
    JsonFactory jsonFactory         = new JacksonFactory();

    GoogleRefreshTokenRequest req = new GoogleRefreshTokenRequest(transport, jsonFactory, refreshToken, client_id, client_secret);
    GoogleTokenResponse res = req.execute();
    String accessToken = res.getAccessToken();
    return accessToken;
}

将刷新令牌存储在某处,您可以执行上面提到的所有操作日历文档。在这里找到它

Store the refresh token somewhere and you can do all the operations that are mentioned in the calendar documentation. Find it here

https://google-api-client-libraries.appspot.com/documentation/calendar/v3/java/latest/index.html

这篇关于使用java离线访问谷歌日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆