2

在以下链接中,有代码应该使用 OAuth 2.0 访问 Google Calendar api。不幸的是,它使用了 Draft 10 客户端库,该库显然已被弃用。

https://developers.google.com/google-apps/calendar/instantiate

最新的客户端库是 google-api-java-client-1.12.0-beta。据我所知,自 Draft 10 客户端库以来,情况发生了很大变化,我无法弄清楚如何为当前的客户端库重写此代码。

不推荐使用的代码如下所示。

import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import   com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;

import com.google.api.services.calendar.Calendar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

...

public void setUp() throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();

    // The clientId and clientSecret are copied from the API Access tab on
    // the Google APIs Console
    String clientId = "YOUR_CLIENT_ID";
    String clientSecret = "YOUR_CLIENT_SECRET";

    // Or your redirect URL for web based applications.
    String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
    String scope = "https://www.googleapis.com/auth/calendar";

    // Step 1: Authorize -->
    String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl,   scope)
    .build();

    // Point or redirect your user to the authorizationUrl.
    System.out.println("Go to the following link in your browser:");
    System.out.println(authorizationUrl);

    // Read the authorization code from the standard input stream.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is the authorization code?");
    String code = in.readLine();
    // End of Step 1 <--

   // Step 2: Exchange -->
    AccessTokenResponse response = new GoogleAuthorizationCodeGrant(httpTransport,     jsonFactory,
    clientId, clientSecret, code, redirectUrl).execute();
   // End of Step 2 <--

  GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
    response.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
    response.refreshToken);

  Calendar service = new Calendar(httpTransport, accessProtectedResource, jsonFactory);
  service.setApplicationName("YOUR_APPLICATION_NAME");
   ...
}
...

谁能告诉如何重写此代码以使其与当前的客户端库一起使用?

4

1 回答 1

0

您可以查看最新的 Google Drive API 文档:

https://developers.google.com/drive/credentials

那么用 Calendar 范围替换 Drive 范围并为服务而不是 Drive 服务对象实例化正确的 Calendar 类应该不难。

如果这种情况再次发生,最好直接查看 Google APIs Client Library for Java 的网站,以确保您可以找到最新版本的代码示例。您可以查看关于 auth 的 wiki,也可以查看示例应用程序,他们确保正在编译和使用最新版本的库(有时很难让所有文档保持最新)

于 2012-11-14T14:51:02.563 回答