-
-
Save mix3/1907353 to your computer and use it in GitHub Desktop.
GDataOAuth2Example.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
public class GDataOAuth2Example { | |
static final String CLIENT_ID = ""; | |
static final String CLIENT_SECRET = ""; | |
static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; // InstalledApplication | |
static final String SCOPES = "https://www.googleapis.com/auth/userinfo.profile" | |
+ " https://www.googleapis.com/auth/userinfo.email"; | |
static final String ENDPOINT = "https://accounts.google.com/o/oauth2"; | |
/** | |
* @param args | |
* @throws IOException | |
*/ | |
public static void main(String[] args) throws IOException { | |
// autherization codeを取得するためのURLを組み立てる | |
String authorizationCode = retrieveAuthorizationCode(); | |
// autherization codeを使ってaccess tokenとrefresh tokenを取得する | |
String tokens = retrieveTokens(authorizationCode); | |
System.out.println(tokens); | |
int start = tokens.indexOf("\"access_token\" : \"") | |
+ "\"access_token\" : \"".length(); | |
int end = tokens.indexOf("\"", start); | |
String accessToken = tokens.substring(start, end); | |
// user info APIを使ってみる。 | |
HttpURLConnection c = (HttpURLConnection) new URL( | |
"https://www.googleapis.com/oauth2/v2/userinfo") | |
.openConnection(); | |
// access tokenを Authorization Headerに指定するだけ! | |
c.setRequestProperty("Authorization", "OAuth " + accessToken); | |
BufferedReader reader = new BufferedReader(new InputStreamReader( | |
c.getInputStream())); | |
String line = null; | |
while ((line = reader.readLine()) != null) { | |
System.out.println(line); | |
} | |
} | |
static String retrieveTokens(String authorizationCode) throws IOException { | |
// パラメータを組み立てる | |
StringBuilder b = new StringBuilder(); | |
b.append("code=").append(URLEncoder.encode(authorizationCode, "utf-8")); | |
b.append("&client_id=").append(URLEncoder.encode(CLIENT_ID, "utf-8")); | |
b.append("&client_secret=").append( | |
URLEncoder.encode(CLIENT_SECRET, "utf-8")); | |
b.append("&redirect_uri=").append( | |
URLEncoder.encode(REDIRECT_URI, "utf-8")); | |
b.append("&grant_type=authorization_code"); | |
byte[] payload = b.toString().getBytes(); | |
// POST メソッドでリクエストする | |
HttpURLConnection c = (HttpURLConnection) new URL(ENDPOINT + "/token") | |
.openConnection(); | |
c.setRequestMethod("POST"); | |
c.setDoOutput(true); | |
c.setRequestProperty("Content-Length", String.valueOf(payload.length)); | |
c.getOutputStream().write(payload); | |
c.getOutputStream().flush(); | |
// トークン類が入ったレスポンスボディの内容を返す(JSONで返される) | |
StringBuilder json = new StringBuilder(); | |
BufferedReader reader = new BufferedReader(new InputStreamReader( | |
c.getInputStream())); | |
String line = null; | |
while ((line = reader.readLine()) != null) { | |
json.append(line).append("\n"); | |
} | |
return json.toString(); | |
} | |
static String retrieveAuthorizationCode() throws IOException { | |
// パラメータを組み立てる | |
StringBuilder b = new StringBuilder(); | |
b.append("response_type=code"); | |
b.append("&client_id=").append(URLEncoder.encode(CLIENT_ID, "utf-8")); | |
b.append("&redirect_uri=").append( | |
URLEncoder.encode(REDIRECT_URI, "utf-8")); | |
b.append("&scope=").append(URLEncoder.encode(SCOPES, "utf-8")); | |
b.append("&state=dummy"); | |
HttpURLConnection.setFollowRedirects(false); | |
// GET メソッドでリクエストする | |
HttpURLConnection c = (HttpURLConnection) new URL(ENDPOINT + "/auth?" | |
+ b.toString()).openConnection(); | |
System.out.println("下記URLを開いて、アクセス承認後に表示された文字列を入力してください。"); | |
System.out.println(c.getHeaderField("Location")); // Locationヘッダに、承認用URLが設定される | |
// ブラウザに表示されたauthorization codeを標準入力から入力させる。 | |
//// 返却されたHTMLのタイトルにもauthorization codeが設定されているので、自動的に取得することもできる。 | |
//// <title>Success state=dummy&code=XXXXXXX</title> | |
BufferedReader reader = new BufferedReader(new InputStreamReader( | |
System.in)); | |
return reader.readLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment