Tomson Xu

@CityU

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

先看上一篇文章理解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 CONSOLE
	private static final String CLIENT_ID = "XXXX"; //use your client ID
	private static final String CLIENT_SECRET = "XXXX";  //use your client secret

	public static void main(String[] args) throws IOException {
		// Generate the URL to which we will direct users
		String authorizeUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID,
				CALLBACK_URL, SCOPE).build();
		System.out.println("Paste this url in your browser: " + authorizeUrl);

		// Wait for the authorization code
		System.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 token
		GoogleAuthorizationCodeGrant 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 request
		GenericUrl 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版。

阅读更多
个人分类: Google
想对作者说点什么? 我来说一句
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭