【问题标题】:Google Contacts v3 API & OAuth v2, in JavaJava 中的 Google 通讯录 v3 API 和 OAuth v2
【发布时间】:2013-04-24 07:27:06
【问题描述】:

在过去的几天里,我一直在尝试使用上述 API 获取 Google 联系人列表。 针说,不成功。 谷歌文档(如果我可以说这是一团糟)对我的问题没有太大帮助。 问题是,我不知道如何使用 OAuth v2 API 授权 ContactsService 对象。 我已经下载了 Google OAuth2.0 库,同样,对于像我这样的初学者来说,它没有适当的文档和/或没有适当的示例。

总而言之,对于上述问题,是否有人有任何有效的“Hello world”类型的示例或任何类型的“指导”?

顺便说一句,我确实设法使用 Scribe API 获取联系人,但您可能知道,响应是 xml/json 格式,需要先解析,这不是我想要的。

谢谢

【问题讨论】:

    标签: java oauth-2.0 google-contacts-api


    【解决方案1】:

    看来我终于取得了一些进展。 显然,问题在于那里有许多不同的 OAuth2 库,其中一些已被弃用或无法与 Contacts v3 一起使用,也就是说,生成的访问令牌将无效(这就是我的结论)。

    所以对于授权和生成访问令牌,我使用了 Google API Client 1.14.1(测试版),我的代码如下:

    Servlet 1(生成身份验证 URL):

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    
            response.setContentType("text/html;charset=UTF-8");           
    
            GoogleAuthorizationCodeRequestUrl authorizationCodeURL=new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URL, SCOPES);
    
            authorizationCodeURL.setAccessType("offline");//For future compatibility
    
            String authorizationURL=authorizationCodeURL.build();
            System.out.println("AUTHORIZATION URL: "+authorizationURL); 
    
            response.sendRedirect(new URL(authorizationURL).toString());
    
    }
    

    Servlet 2(处理访问令牌)

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
    
    
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet SignInFinished</title>");
        out.println("</head>");
        out.println("<body>");
    
    
        HttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        GoogleAuthorizationCodeTokenRequest authorizationTokenRequest = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory, CLIENT_ID, CLIENT_SECRET, request.getParameter("code"), REDIRECT_URL);
    
        GoogleTokenResponse tokenResponse = authorizationTokenRequest.execute();
    
        out.println("OAuth2 Access Token: " + tokenResponse.getAccessToken());
    
        GoogleCredential gc = new GoogleCredential();
        gc.setAccessToken(tokenResponse.getAccessToken());
    
        ContactsService contactsService = new ContactsService("Lasso Project");
        contactsService.setOAuth2Credentials(gc);
    
        try {
            URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
    
            Query myQuery = new Query(feedUrl);
            myQuery.setMaxResults(1000);
    
            ContactFeed resultFeed = contactsService.query(myQuery, ContactFeed.class);
    
            for (int i = 0; i < resultFeed.getEntries().size(); i++) {
                out.println(resultFeed.getEntries().get(i).getTitle().getPlainText() + "<br/>");
            }
    
        } catch (Exception e) {
            System.out.println(e);
        }
    
        out.println("</body>");
        out.println("</html>");
    }
    

    注意: 如果您使用 Web 应用程序的客户端 ID,REDIRECT_URL 必须是您在通过 Google 控制台注册应用程序时输入的重定向 URL 之一。

    嗯,我希望这对你们中的一些人有所帮助:)。

    【讨论】:

    • 非常感谢。经过多次失败的尝试,我终于在您的帮助下成功了!
    • 你能告诉我你用于联系服务的jar的版本
    • 很好的例子。太感谢了。使用这个 API 非常令人沮丧,有这么多不同的版本和方法。你的是最简单的,最接近我需要的。真的很感激。
    【解决方案2】:

    我在尝试检索 Google 联系人时也遇到了麻烦。 使用 OAuth2.0,您首先需要获得一个access token. 然后就很容易了,你可以请求组的id你正在寻找:

    import com.google.gdata.client.contacts.ContactsService;
    import com.google.gdata.data.contacts.ContactEntry;
    import com.google.gdata.data.contacts.ContactFeed;
    import com.google.gdata.data.contacts.ContactGroupEntry;
    import com.google.gdata.data.contacts.ContactGroupFeed;
    
    private static final String GROUPS_URL = "https://www.google.com/m8/feeds/groups/default/full";
    
    private int getIdOfMyGroup() {
        ContactsService contactsService = new ContactsService("MY_PRODUCT_NAME");
        contactsService.setHeader("Authorization", "Bearer " + MY_ACCESS_TOKEN);
    
        try {
            URL feedUrl = new URL(GROUPS_URL);
            ContactGroupFeed resultFeed = contactsService.getFeed(feedUrl, ContactGroupFeed.class);
            // "My Contacts" group id will always be the first one in the answer
            ContactGroupEntry entry = resultFeed.getEntries().get(0);
    
            return entry.getId();
        } catch (...) { ... }
    }
    

    最终您将能够使用组 ID 请求其联系人:

    private static final String CONTACTS_URL = "https://www.google.com/m8/feeds/contacts/default/full";
    private static final int MAX_NB_CONTACTS = 1000;
    
    private List<ContactEntry> getContacts() {
        ContactsService contactsService = new ContactsService("MY_PRODUCT_NAME");
        contactsService.setHeader("Authorization", "Bearer " + MY_ACCESS_TOKEN);
    
        try {
            URL feedUrl = new URL(CONTACTS_URL);
            Query myQuery = new Query(feedUrl);
                        // to retrieve contacts of the group I found just above
            myQuery.setStringCustomParameter("group", group);
            myQuery.setMaxResults(MAX_NB_CONTACTS);
            ContactFeed resultFeed = contactsService.query(myQuery, ContactFeed.class);
            List<ContactEntry> contactEntries = resultFeed.getEntries();
    
            return contactEntries;
        } catch (...) { ... }
    }
    

    【讨论】:

    • 已经试过这个方法了,和之前一样,query/getFeed方法抛出异常:java.lang.NullPointerException: No authentication header information
    • 它对我有用。我猜你的问题来自 OAuth 部分。您确定您的访问令牌有效吗?
    • 我得到了访问令牌,它是否有效,不确定是否有办法检查。 :S.
    • 例如,对于webservice,您会得到类似 { "access_token":"1/fFAGRNJru1FTz70BzhT3Zg", "expires_in":3920, "token_type":"Bearer" } 的有效访问权限令牌。我不知道您正在开发什么样的项目,但检查您的访问令牌是否正确应该不难
    • 这是一个 java web 应用程序。使用 2 个 servlet,一个用于初始化身份验证过程,另一个作为回调 servlet,我在其中获取访问令牌。使用GoogleOAuthParameters 设置参数,使用GoogleOAuthHelper 生成授权url。我会在这里粘贴我的代码,但我可以输入的字符数是有限的。
    猜你喜欢
    • 2015-08-11
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多