在过去的几天里,我一直在尝试使用上述API来获取Google联系人列表。
针说,没有成功。
Google文档(如果我可能会说是一团糟)对我的问题不是很有帮助。
问题是,我不知道如何使用OAuth v2 API授权ContactsService对象。
我已经下载了Google OAuth2.0库,对于像我这样的初学者来说,该库也没有适当的文档和/或适当的示例。
因此,总而言之,是否有人对上述问题有任何有效的“Hello world”类型的示例或任何类型的“指导”?
附带说明一下,我确实使用Scribe API来获取联系人,但是您可能知道,响应采用xml/json格式,需要首先进行解析,而这不是我想要的。
谢谢
最佳答案
看来我终于取得了一些进展。
显然,问题在于存在许多不同的OAuth2库,其中一些已被弃用,或者将无法与Contacts v3一起使用,也就是说,生成的访问 token 将是无效的(这就是我得出的结论)。
因此,为了进行授权和生成访问 token ,我使用了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(处理访问 token )
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之一。
好吧,希望对您中的某些人有所帮助:)。