Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Created September 17, 2012 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lobster1234/3739628 to your computer and use it in GitHub Desktop.
Save lobster1234/3739628 to your computer and use it in GitHub Desktop.
Oauth2 Authorization with Google APIs - A quick verification script
package com.ign.traffic;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class TrafficManager {
private static String clientId = "replaceWithYours.apps.googleusercontent.com";
private static String clientSecret = "replaceWithYours";
private static String redirectUri = "urn:ietf:wg:oauth:2.0:oob";
private static String scope = "https://www.googleapis.com/auth/analytics.readonly";
private static final String authURL = "https://accounts.google.com/o/oauth2/auth";
private static final String tokenURL = "https://accounts.google.com/o/oauth2/token";
public static void main(String[] args) throws Exception{
//Lets get the authorization code
System.out.println("Type this URL in the browser, and come back " + authURL+"?scope="+scope+"&response_type=code&client_id="+clientId+"&redirect_uri="+redirectUri);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the code here : ");
String code = in.readLine();
System.out.println("You typed " + code);
//lets get the access token etc. here
HttpPost post = new HttpPost(tokenURL);
post.setEntity(new StringEntity("code="+code+"&client_id="+clientId+"&client_secret="+clientSecret+"&redirect_uri="+redirectUri+"&grant_type=authorization_code"));
post.addHeader("Content-Type","application/x-www-form-urlencoded");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment