Skip to content

Instantly share code, notes, and snippets.

@shin1ogawa
Created February 24, 2012 08:31
Show Gist options
  • Save shin1ogawa/1899391 to your computer and use it in GitHub Desktop.
Save shin1ogawa/1899391 to your computer and use it in GitHub Desktop.
Apps API Japan #3 Javaサンプル
import java.io.*;
import java.net.*;
public class GDataCalendarExample {
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/calendar";
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);
// Calendar APIを使ってみる。
listCalendarList(accessToken);
System.out.println("カレンダーIDを入力して下しあ:");
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
String calendarId = reader.readLine();
listEvents(accessToken, calendarId);
System.out.println("予定のタイトルを入力してください:");
String eventTitle = reader.readLine();
postEvents(accessToken, calendarId, eventTitle);
}
static void postEvents(String accessToken, String calendarId,
String eventTitle) throws IOException {
// パラメータを組み立てる
StringBuilder b = new StringBuilder();
b.append("{");
b.append("\"start\": { \"date\": \"2012-02-28\" },");
b.append("\"end\": { \"date\": \"2012-02-28\" },");
b.append("\"summary\": \"").append(eventTitle).append("\"");
b.append("}");
System.out.println(b);
byte[] payload = b.toString().getBytes("utf-8");
HttpURLConnection c = (HttpURLConnection) new URL(
"https://www.googleapis.com/calendar/v3/calendars/"
+ calendarId + "/events").openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.setRequestProperty("Authorization", "OAuth " + accessToken);
c.setRequestProperty("Content-Length", String.valueOf(payload.length));
c.setRequestProperty("Content-Type", "application/json; charset=utf-8");
c.getOutputStream().write(payload);
c.getOutputStream().flush();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
c.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(c.getResponseCode());
System.out.println(c.getResponseMessage());
}
}
static void listEvents(String accessToken, String calendarId)
throws IOException {
HttpURLConnection c = (HttpURLConnection) new URL(
"https://www.googleapis.com/calendar/v3/calendars/"
+ calendarId + "/events").openConnection();
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 void listCalendarList(String accessToken) throws IOException {
HttpURLConnection c = (HttpURLConnection) new URL(
"https://www.googleapis.com/calendar/v3/users/me/calendarList")
.openConnection();
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);
}
}
/**
* @param refreshToken
* @return リフレッシュトークンを使ったアクセストークン取得のレスポンス
* <code>{ "access_token": access_token, ...}</code>
* @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(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 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&amp;code=XXXXXXX</title>
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
return reader.readLine();
}
}
import java.io.*;
import java.net.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class GDataContactsExample {
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.google.com/m8/feeds";
static final String ENDPOINT = "https://accounts.google.com/o/oauth2";
/**
* @param args
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
public static void main(String[] args) throws IOException, SAXException,
ParserConfigurationException {
// 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);
// String accessToken =
// "ya29.AHES6ZRwaS3PnSh5XMC_4VU3gYez0U6dIyb8CNJ7O9_Zu1VvAsdmem0";
// Contacts APIを使ってみる: 連絡先の一覧を取得する
listContacts(accessToken);
// Contacts APIを使ってみる: 連絡先を追加する
createContact(accessToken);
}
static void createContact(String accessToken) throws IOException {
// パラメータを組み立てる
StringBuilder b = new StringBuilder();
b.append("<?xml version='1.0' encoding='UTF-8'?>\n");
b.append("<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gContact='http://schemas.google.com/contact/2008' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005'>");
b.append(" <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact' />");
b.append(" <gd:name>");
b.append(" <gd:givenName>AppsAPIJA</gd:givenName>");
b.append(" <gd:familyName>Third</gd:familyName>");
b.append(" <gd:fullName>AppsAPIJA #3</gd:fullName>");
b.append(" </gd:name>");
b.append(" <gd:email rel='http://schemas.google.com/g/2005#other' address='[email protected]' primary='true'/>");
b.append(" <title>AppsAPIJA #3</title>");
b.append("</entry>");
System.out.println(b);
byte[] payload = b.toString().getBytes("utf-8");
HttpURLConnection c = (HttpURLConnection) new URL(
"https://www.google.com/m8/feeds/contacts/default/full")
.openConnection();
c.setRequestMethod("POST");
c.setDoOutput(true);
c.setRequestProperty("Authorization", "OAuth " + accessToken);
c.setRequestProperty("Content-Length", String.valueOf(payload.length));
c.setRequestProperty("Content-Type",
"application/atom+xml; charset=UTF-8;");
c.getOutputStream().write(payload);
c.getOutputStream().flush();
System.out.println(c.getResponseCode() + ":" + c.getResponseMessage());
}
static void listContacts(String accessToken) throws IOException,
SAXException, ParserConfigurationException {
HttpURLConnection c = (HttpURLConnection) new URL(
"https://www.google.com/m8/feeds/contacts/default/full")
.openConnection();
c.setRequestProperty("Authorization", "OAuth " + accessToken);
Document root = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(c.getInputStream());
// /entry
NodeList entryList = root.getElementsByTagName("entry");
for (int i = 0, len = entryList.getLength(); i < len; i++) {
Node entryNode = entryList.item(i);
NodeList childrenOfEntryNode = entryNode.getChildNodes();
for (int j = 0, lenJ = entryList.getLength(); j < lenJ; j++) {
Node childOfEntryNode = childrenOfEntryNode.item(j);
if (childOfEntryNode == null
|| childOfEntryNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if ("gd:email".equals(childOfEntryNode.getNodeName())) {
System.out.println(childOfEntryNode.getAttributes()
.getNamedItem("address"));
}
}
}
}
/**
* @param refreshToken
* @return リフレッシュトークンを使ったアクセストークン取得のレスポンス
* <code>{ "access_token": access_token, ...}</code>
* @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(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 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&amp;code=XXXXXXX</title>
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
return reader.readLine();
}
}
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&amp;code=XXXXXXX</title>
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
return reader.readLine();
}
}
@soundTricker
Copy link

👍

@wezardnet
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment