Skip to content

Instantly share code, notes, and snippets.

@shin1ogawa
Created August 4, 2014 19:28
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class GoogleApiClient {
static final String CLIENT_ID = "your-client-id";
static final String CLIENT_SECRET = "your-client-secret";
static final String SCOPES = "https://www.googleapis.com/auth/gmail.readonly";
/**
* <ol>
* <li>Authorization Codeを取得するURLを組み立て、表示する
* <li>Authorization Codeを使ってAccess TokenとToken Typeを取得する
* <li>取得したAccess Tokenを使ってGmail API(Users.labels: list)を実行する
* </ol>
* @param args
* @throws IOException
* @author shin1ogawa
*/
public static void main(String[] args) throws IOException {
System.out.println(buildURLToGetAuthorizationCode(CLIENT_ID, SCOPES));
System.out.println("上記のURLをブラウザで開いて、許可操作後に表示された文字列を入力して下さい:");
String authorizationCode = new BufferedReader(new InputStreamReader(System.in)).readLine();
String exchangeToken = exchangeToken(CLIENT_ID, CLIENT_SECRET, authorizationCode);
String accessToken;
{
int start =
exchangeToken.indexOf("\"access_token\" : \"")
+ "\"access_token\" : \"".length();
int end = exchangeToken.indexOf("\"", start);
accessToken = exchangeToken.substring(start, end);
}
String tokenType;
{
int start =
exchangeToken.indexOf("\"token_type\" : \"") + "\"token_type\" : \"".length();
int end = exchangeToken.indexOf("\"", start);
tokenType = exchangeToken.substring(start, end);
}
gmailApi(tokenType, accessToken);
}
static String buildURLToGetAuthorizationCode(String clientId, String scopes) throws IOException {
return new StringBuilder("https://accounts.google.com/o/oauth2/auth?")
.append("response_type=code").append("&client_id=").append(clientId)
.append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob").append("&scope=")
.append(URLEncoder.encode(scopes, "utf-8")).toString();
}
static String exchangeToken(String clientId, String clientSecret, String authorizationCode)
throws IOException {
byte[] parameters =
new StringBuilder().append("&code=")
.append(URLEncoder.encode(authorizationCode, "utf-8")).append("&client_id=")
.append(URLEncoder.encode(clientId, "utf-8")).append("&client_secret=")
.append(URLEncoder.encode(clientSecret, "utf-8"))
.append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob")
.append("&grant_type=authorization_code").toString().getBytes("utf-8");
URL url = new URL("https://accounts.google.com/o/oauth2/token");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Length", String.valueOf(parameters.length));
connection.setDoOutput(true);
connection.getOutputStream().write(parameters);
connection.getOutputStream().flush();
InputStream inputStream = connection.getInputStream();
StringBuilder tokens = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
tokens.append(line);
}
}
System.out.println(tokens);
return tokens.toString();
}
static void gmailApi(String tokenType, String accessToken) throws IOException {
URL url = new URL("https://www.googleapis.com/gmail/v1/users/me/labels");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", tokenType + " " + accessToken);
InputStream inputStream = connection.getInputStream();
StringBuilder response = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
System.out.println(response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment