Google + oauth + 2.0 + Java + client + Library + simple + example

Source: Internet
Author: User
Tags oauth

Read the previous article to understand the principles of Google oauth 2.0 at http://blog.csdn.net/totogogo/article/details/6860966.

Note that all the codes in the above article do not use the Google client library code. This article describes oauth 2.0 simple example using Google Java client library.

This article English Reference document: http://code.google.com/p/google-api-java-client/wiki/OAuth2Draft10

Note: When writing this article, Google auth 2.0 is progressing to draft 10.

Step 1: As mentioned in the previous article, register a create a client ID and secret for installed app at http://code.google.com/apis/lele?access

Step 2: Download Google-API-Java-client (currently v1.5.0 beta) at http://code.google.com/p/google-api-java-client/downloads/list, because there is no time to study the specific jar, add all jar files (including those in "dependencies" folder) to classpath.

Step 3: create the following example (use your 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. When I run it, only access token can be obtained successfully. When you use this access token to access Google data, an exception occurs. I wonder if it's because it's still in Beta.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.