google+oauth+2.0+java+client+library+simple+example

來源:互聯網
上載者:User

先看上一篇文章理解google oauth 2.0的原理 at http://blog.csdn.net/totogogo/article/details/6860966。

注意,上面這篇文章裡的codes都是不使用google client library的代碼。本篇寫的是一個使用google java client library的oauth 2.0 simple example。

本篇的英文參考文檔:http://code.google.com/p/google-api-java-client/wiki/OAuth2Draft10

注意:寫本文時,google auth 2.0進展到draft 10.

Step 1: 像上篇文章提到的,先在http://code.google.com/apis/console#access註冊一個create a client ID and secret for installed app

Step 2: download google-api-java-client (當前是v1.5.0 beta) at http://code.google.com/p/google-api-java-client/downloads/list, 由於沒時間研究具體需要哪些jar,就把所有的jar files (包括”dependencies“ folder裡的)都添加到classpath。

Step 3: 建立下面的例子 (使用你的client id and secret)

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.ByteArrayContent;import com.google.api.client.http.GenericUrl;import com.google.api.client.http.HttpRequest;import com.google.api.client.http.HttpRequestFactory;import com.google.api.client.http.HttpResponse;import com.google.api.client.http.HttpTransport;import com.google.api.client.http.javanet.NetHttpTransport;import com.google.api.client.json.JsonFactory;import com.google.api.client.json.jackson.JacksonFactory;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class TestAuth2 {private static final String SCOPE = "https://www.googleapis.com/auth/urlshortener";private static final String CALLBACK_URL = "urn:ietf:wg:oauth:2.0:oob";private static final HttpTransport TRANSPORT = new NetHttpTransport();private static final JsonFactory JSON_FACTORY = new JacksonFactory();// FILL THESE IN WITH YOUR VALUES FROM THE API CONSOLEprivate static final String CLIENT_ID = "XXXX"; //use your client IDprivate static final String CLIENT_SECRET = "XXXX";  //use your client secretpublic static void main(String[] args) throws IOException {// Generate the URL to which we will direct usersString authorizeUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,CALLBACK_URL, SCOPE).build();System.out.println("Paste this url in your browser: " + authorizeUrl);// Wait for the authorization codeSystem.out.println("Type the code you received here: ");BufferedReader in = new BufferedReader(new InputStreamReader(System.in));String authorizationCode = in.readLine();// Exchange for an access and refresh tokenGoogleAuthorizationCodeGrant authRequest = new GoogleAuthorizationCodeGrant(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,authorizationCode, CALLBACK_URL);authRequest.useBasicAuthorization = false;AccessTokenResponse authResponse = authRequest.execute();String accessToken = authResponse.accessToken;GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken, TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET,authResponse.refreshToken);HttpRequestFactory rf = TRANSPORT.createRequestFactory(access);System.out.println("Access token: " + authResponse.accessToken);// Make an authenticated requestGenericUrl shortenEndpoint = new GenericUrl("https://www.googleapis.com/urlshortener/v1/url");String requestBody = "{\"longUrl\":\"http://farm6.static.flickr.com/5281/5686001474_e06f1587ff_o.jpg\"}";HttpRequest request = rf.buildPostRequest(shortenEndpoint,new ByteArrayContent(requestBody));request.headers.contentType = "application/json";HttpResponse shortUrl = request.execute();BufferedReader output = new BufferedReader(new InputStreamReader(shortUrl.getContent()));System.out.println("Shorten Response: ");for (String line = output.readLine(); line != null; line = output.readLine()) {System.out.println(line);}// Refresh a token (SHOULD ONLY BE DONE WHEN ACCESS TOKEN EXPIRES)access.refreshToken();System.out.println("Original Token: " + accessToken + " New Token: "+ access.getAccessToken());}}

Step 4: run it。我執行它時,只能成功執行到擷取access token。在使用該access token to access google data時,就會有exception。不知是不是因為現在還是beta版。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.