!!!OAuth in the Google Data Protocol Client Libraries講解: http://code.google.com/intl/zh-TW/apis/gdata/docs/auth/oauth.html
package example_tomson.oauth1;import java.net.URL;import com.google.gdata.client.GoogleService;import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;import com.google.gdata.client.authn.oauth.OAuthRsaSha1Signer;import com.google.gdata.client.authn.oauth.OAuthSigner;import com.google.gdata.data.BaseEntry;import com.google.gdata.data.BaseFeed;import com.google.gdata.data.Feed;/** * * google oauth 1.0請參看http://blog.csdn.net/totogogo/article/details/6835820 * * 該example是示範google oauth 1.0, it is for standalone application,即沒有callback_url parameter。沒有設定 * callback url parameter,就會認為是anonymous。當user click了authorize button後,就會出現一個google handle result msg web page * * 而如果是web app使用oauth 1.0,就會設定callback url,當user click了authorize button後, * 就會redirect to callback url with authorized token and related params * * standalone app使用auth 1.0時同樣需要register a domain來擷取consumer key and secret. * * */public class OAuth1Example {public static void main(String[] args) throws Exception{//該comsumer key是String oauthConsumerKey="chtl.hkbu.edu.hk";String oauthConsumerSecret="XXXXXX";String signatureMethod="HMAC"; //HMAC or RSA//for calendar apiString scope = "http://www.google.com/calendar/feeds/"; String strCalendarFeedUrl="http://www.google.com/calendar/feeds/default/allcalendars/full"; //////////////////////////////////////////////////////////////////////////// // STEP 1: Set up the OAuth objects //////////////////////////////////////////////////////////////////////////// // You first need to initialize a few OAuth-related objects. // GoogleOAuthParameters holds all the parameters related to OAuth. // OAuthSigner is responsible for signing the OAuth base string.//建立GoogleOAuthParameters執行個體,它包含所有oauth parameterGoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); oauthParameters.setOAuthConsumerKey(oauthConsumerKey); oauthParameters.setScope(scope); // Initialize the OAuth Signer. If you are using RSA-SHA1, you must provide // your private key as a Base-64 string conforming to the PKCS #8 standard. // Visit http://code.google.com/apis/gdata/authsub.html#Registered to learn // more about creating a key/certificate pair. If you are using HMAC-SHA1, // you must set your OAuth Consumer Secret, which can be obtained at // https://www.google.com/accounts/ManageDomains. //建立oauth signer執行個體 OAuthSigner signer=null; if(signatureMethod=="HMAC") { //如果使用HMAC-SHA1 method,則需要在GoogleOAuthParameters obj裡提供OAuth Consumer Secret(使用RSA-SHA1 method則不需要提供它) oauthParameters.setOAuthConsumerSecret(oauthConsumerSecret); signer = new OAuthHmacSha1Signer(); } else if(signatureMethod=="RSA"){ //如果使用RSA-SHA1 method,你必須提供你的符合PKCS #8標準的private key as a Base-64 string String signatureKey="<RSA private key>"; signer = new OAuthRsaSha1Signer(signatureKey); } //////////////////////////////////////////////////////////////////////////// // STEP 2: Get the Authorization URL //////////////////////////////////////////////////////////////////////////// // Create a new GoogleOAuthHelperObject. This is the object you will use for all OAuth-related interaction. //以oauth signer obj為參數建立GoogleOAuthHelper obj,然後以GoogleOAuthParameters作為參數call getUnauthorizedRequestToken method來擷取unauthorized request token GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer); oauthHelper.getUnauthorizedRequestToken(oauthParameters); //send a request to get the unauthorized request token //!!!然後它會把response返回的 unauthorized request token和token secret寫入oauthParameters object裡// System.out.println("=====================================================");// System.out.println("auth token is: " + oauthParameters.getOAuthToken());// System.out.println("auth token secret is: "+oauthParameters.getOAuthTokenSecret());// System.out.println("auth signature is: " + oauthParameters.getOAuthSignature());// System.out.println("auth signature method is: " + oauthParameters.getOAuthSignatureMethod());// System.out.println("auth Nonce is: " + oauthParameters.getOAuthNonce());// System.out.println("auth Verifier is: " + oauthParameters.getOAuthVerifier());// System.out.println("====================================================="); // Get the authorization url. The user of your application must visit // this url in order to authorize with Google. If you are building a // browser-based application, you can redirect the user to the authorization url. //call createUserAuthorizationUrl method來產生供user進行authorize OAuth request token的URL //user可以在browser裡access to this URL,然後click authorization button來允許該app能夠進入你的google賬戶裡擷取data/info/file String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters); System.out.println(requestUrl); System.out.println("Please visit the URL above to authorize your OAuth request token. Once that is complete, press any key to continue..."); System.in.read(); //////////////////////////////////////////////////////////////////////////// // STEP 3: Get the Access Token //////////////////////////////////////////////////////////////////////////// // Once the user authorizes with Google, the request token can be exchanged // for a long-lived access token. If you are building a browser-based // application, you should parse the incoming request token from the url and // set it in GoogleOAuthParameters before calling getAccessToken(). //!!注意:在上一個step,user賦予授權之後,並不需要從browser裡擷取任何返回的parameter value //(感覺只需要對request token進行authorize即可),然後就可以call //oauthHelper.getAccessToken(oauthParameters) //來擷取access token, //!!!同時會把oauthParameters裡的oauth token的值由authorized request token轉換成access token!!! String token = oauthHelper.getAccessToken(oauthParameters); System.out.println("OAuth Access Token: " + token); //////////////////////////////////////////////////////////////////////////// // STEP 4: access calendar api //////////////////////////////////////////////////////////////////////////// URL feedUrl = new URL(strCalendarFeedUrl); System.out.println("Sending request to " + feedUrl.toString()); System.out.println(); String googleServiceName = "cl"; GoogleService googleService = new GoogleService(googleServiceName, "oauth-sample-app"); // Set the OAuth credentials which were obtained from the step above. //參數oauthParameters包含上一個step擷取的access token info googleService.setOAuthCredentials(oauthParameters, signer); //!!!關鍵方法:Make the request to Google BaseFeed resultFeed = googleService.getFeed(feedUrl, Feed.class); System.out.println("Response Data:"); System.out.println("====================================================="); System.out.println("| TITLE: " + resultFeed.getTitle().getPlainText()); if (resultFeed.getEntries().size() == 0) { System.out.println("|\tNo entries found."); } else { for (int i = 0; i < resultFeed.getEntries().size(); i++) { BaseEntry entry = (BaseEntry) resultFeed.getEntries().get(i); System.out.println("|\t" + (i + 1) + ": " + entry.getTitle().getPlainText()); } } System.out.println("====================================================="); System.out.println(); //////////////////////////////////////////////////////////////////////////// // STEP 5: Revoke the OAuth token //////////////////////////////////////////////////////////////////////////// System.out.println("Revoking OAuth Token..."); oauthHelper.revokeToken(oauthParameters); System.out.println("OAuth Token revoked...");}}