本文主要是介绍google oauth 1.0 standalone app example,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
!!!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 tokenGoogleOAuthHelper 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/fileString 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 apiURL 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 infogoogleService.setOAuthCredentials(oauthParameters, signer);//!!!关键方法:Make the request to GoogleBaseFeed 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 tokenSystem.out.println("Revoking OAuth Token...");oauthHelper.revokeToken(oauthParameters);System.out.println("OAuth Token revoked...");}}
这篇关于google oauth 1.0 standalone app example的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!