在以下鏈接中有代碼可以使用OAuth 2.0訪問Google日曆API。不幸的是,它使用草案10客戶端庫,這顯然已被棄用。如何使用Google OAuth 2.0配置授權服務對象
https://developers.google.com/google-apps/calendar/instantiate
最新的客戶端庫是谷歌的API-Java的客戶端1.12.0-β。從草案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");
...
}
...
任何人都可以告訴如何重寫此代碼,以便它可以與當前客戶端庫一起使用嗎?
謝謝Nivco對於你的回覆,你給了我很多需要學習和思考的信息。 – Laurence