看来我终于取得了一些进展。显然,问题在于那里有许多不同的 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 之一。
好吧,我希望这会对你们中的一些人有所帮助:)。