Skip to content

Instantly share code, notes, and snippets.

@shin1ogawa
Created July 26, 2012 04:39
Show Gist options
  • Save shin1ogawa/31828b4324385a620c89 to your computer and use it in GitHub Desktop.
Save shin1ogawa/31828b4324385a620c89 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class DocumentsListAPIWithOAuth2 {
static final String CLIENT_ID = "";
static final String CLIENT_SECRET = "";
static final String REDIRECT_URI_FOR_INSTALLED_APP = "urn:ietf:wg:oauth:2.0:oob"; // InstalledApplication
static final String SCOPES = "https://docs.google.com/feeds/ https://docs.googleusercontent.com/";
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);
start = tokens.indexOf("\"refresh_token\" : \"") + "\"refresh_token\" : \"".length();
end = tokens.indexOf("\"", start);
String refreshToken = tokens.substring(start, end);
System.out.println("accessToken=" + accessToken + ", refreshToken=" + refreshToken);
accessToken = refreshToken(refreshToken); // アクセストークンが切れた場合はこうやってリフレッシュする
System.out.println("refreshed accessToken=" + accessToken);
executeAPI(accessToken);
}
static void executeAPI(String accessToken) throws IOException {
// execute "Retrieve all documents" - Documents LIST API
String urlString =
new StringBuilder("https://docs.google.com/feeds/default/private/full").append(
"?max-results=10").toString();
HttpURLConnection c = (HttpURLConnection) new URL(urlString).openConnection();
c.setRequestProperty("Authorization", "OAuth " + accessToken); // OAUth2 アクセストークン
c.setRequestProperty("GData-Version", "3.0"); // Documents List API のお約束.
BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
/**
* リフレッシュトークンを使って新しいアクセストークンを取得する。
* @param refreshToken
* @return 新しく取得したアクセストークン
* @throws IOException
*/
static String refreshToken(String refreshToken) throws IOException {
// パラメータを組み立てる
StringBuilder b = new StringBuilder();
b.append("&client_id=").append(URLEncoder.encode(CLIENT_ID, "utf-8"));
b.append("&client_secret=").append(URLEncoder.encode(CLIENT_SECRET, "utf-8"));
b.append("&refresh_token=").append(URLEncoder.encode(refreshToken, "utf-8"));
b.append("&grant_type=refresh_token");
byte[] payload = b.toString().getBytes();
// POST メソッドでリクエストする
HttpURLConnection c =
(HttpURLConnection) new URL("https://accounts.google.com/o/oauth2/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");
}
int start = json.indexOf("\"access_token\" : \"") + "\"access_token\" : \"".length();
int end = json.indexOf("\"", start);
String accessToken = json.substring(start, end);
return accessToken;
}
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_FOR_INSTALLED_APP, "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_FOR_INSTALLED_APP, "utf-8"));
b.append("&scope=").append(URLEncoder.encode(SCOPES, "utf-8"));
b.append("&status=1&access_type=offline&approval_prompt=force");
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&amp;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