先日ブログにも書きましたがV2でのアクセスであり、ClientLoginだったので
今度はv3でのアクセスをやってみます。今回もJavaです。
Googleの日本語の資料はいつも通り古くほぼv2を使っているので
しばらくは英語の文献の方が良いと思います。
準備
まずここからクライアントライブラリをダウンロードしてきます。
で
・google-api-client-1.6.0-beta.jar
・google-http-client-1.6.0-beta.jar
・google-oauth-client-1.6.0-beta.jar
・dependencies/gson-1.7.1.jar
・dependencies/guava-r09.jar
・dependencies/jackson-core-asl-1.9.1.jar
を読み込みます。
Analytics用のライブラリはここにあります。
OAuthでのアクセスする準備
Google+のアクセス時に説明しましたが、API使用したり、クライアントID取得の為に
GoogleAPIConsoleでAnalyticsをONしておく必要があります。
「Services」をクリックしてAnalyticsをON
「API Access」をクリックして、クライアントIDを発行します。
私自身はWebアプリで使いたいですけど、一旦アクセスする為に「installed applications」を選びました。
違いはWebアプリケーションの場合と違い、コールバックURLが固定値になり、
手作業で認可コードを設定するっていう手順が増えるだけです。
認可を行う
さて準備ができたので、アクセスしてみます。
- String authorizationUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID, REDIRECT_URL, "https://www.googleapis.com/auth/analytics.readonly").build();
- System.out.println(authorizationUrl);
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- String authorizationCode = null;
- try {
- authorizationCode = in.readLine();
- } catch (IOException ioe) {
- throw new RuntimeException("Error",ioe);
- }
String authorizationUrl = new GoogleAuthorizationRequestUrl(CLIENT_ID, REDIRECT_URL, "https://www.googleapis.com/auth/analytics.readonly").build();
System.out.println(authorizationUrl);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String authorizationCode = null;
try {
authorizationCode = in.readLine();
} catch (IOException ioe) {
throw new RuntimeException("Error",ioe);
}
GoogleAuthorizationRequestUrlに取得したクライアントIDとリダイレクトURLを設定します。
三番目の引数はスコープ(何にアクセスできるか)です。
認証用のURLを作成してコンソールに出力しreadLine()で認可コードを待ち受けます。
ブラウザを立ち上げて、コンソールに出力されたURLにアクセスすると
Googleの認証画面(マルチアカウントの場合、ユーザ選択画面等もあります)が表示され
認可画面が現れて認可を行うと、認可コードを出力してくれるのでそれをコンソールに入力します。
アクセストークンの取得
コンソールに入力された認可コードを元にアクセストークンをとりにいきます。
APIコンソールで取得したIDとSecret、それと認可コードでAccessTokenResponseを生成
- NetHttpTransport httpTransport = new NetHttpTransport();
- JacksonFactory jacksonFactory = new JacksonFactory();
- AccessTokenResponse response = null;
- try {
- response = new GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant(
- httpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET, authorizationCode,
- REDIRECT_URL).execute();
- } catch (IOException ioe) {
- throw new RuntimeException("Error",ioe);
- }
NetHttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jacksonFactory = new JacksonFactory();
AccessTokenResponse response = null;
try {
response = new GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant(
httpTransport, jacksonFactory, CLIENT_ID, CLIENT_SECRET, authorizationCode,
REDIRECT_URL).execute();
} catch (IOException ioe) {
throw new RuntimeException("Error",ioe);
}
認可コードが間違ってなかったらこれでOKのはず。
responseにアクセストークン、リフレッシュトークン等が取得されます。
Analyticsのオブジェクトを生成
取得したAccessTokenResponseを元に
- GoogleAccessProtectedResource googleAccessProtectedResource =
- new GoogleAccessProtectedResource(response.accessToken, httpTransport, jacksonFactory,CLIENT_ID, CLIENT_SECRET, response.refreshToken);
- Analytics analytics = Analytics.builder(httpTransport, jacksonFactory)
- .setHttpRequestInitializer(googleAccessProtectedResource)
- .setApplicationName("test")
- .build();
GoogleAccessProtectedResource googleAccessProtectedResource =
new GoogleAccessProtectedResource(response.accessToken, httpTransport, jacksonFactory,CLIENT_ID, CLIENT_SECRET, response.refreshToken);
Analytics analytics = Analytics.builder(httpTransport, jacksonFactory)
.setHttpRequestInitializer(googleAccessProtectedResource)
.setApplicationName("test")
.build();
というような感じでAnalyticsオブジェクトを生成します。
データを取得してみる
さてやっとアクセスですね。
- Get apiQuery;
- try {
- apiQuery = analytics
- .data()
- .ga()
- .get("ga:" + "13012476", "2011-09-01", "2011-09-30",
- "ga:visits,ga:pageviews");
- } catch (IOException e) {
- throw new RuntimeException("Error", e);
- }
-
- apiQuery.setSort("-ga:visits");
- apiQuery.setMaxResults(50);
-
- try {
- GaData data = apiQuery.execute();
- Map<string, string=""> totalsMap = data.getTotalsForAllResults();
- for (Map.Entry<string,string> entry : totalsMap.entrySet()) {
- System.out.println(entry.getKey() + " : " + entry.getValue());
- }
- } catch (IOException e) {
- throw new RuntimeException("Error", e);
- }
- string,string></string,>
Get apiQuery;
try {
apiQuery = analytics
.data()
.ga()
.get("ga:" + "13012476", "2011-09-01", "2011-09-30",
"ga:visits,ga:pageviews");
} catch (IOException e) {
throw new RuntimeException("Error", e);
}
apiQuery.setSort("-ga:visits");
apiQuery.setMaxResults(50);
try {
GaData data = apiQuery.execute();
Map totalsMap = data.getTotalsForAllResults();
for (Map.Entry entry : totalsMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
} catch (IOException e) {
throw new RuntimeException("Error", e);
}
取得してきたanalyticsオブジェクトのdata().ga().get()をおこなってGetオブジェクトを生成します。
第1引数はProfileIdになります。v2で言っていたTableIdですね。id自体は数値などで入っている為、
「ga:」をつけてやる必要があります。
これをexecute()するとデータが取れてきます。
この取得方法だと出力は「ga:visits,ga:pageview」が取得できます。
取得できるDimensionやMetricsなどはここにあります。
ProfileのIdについて
前述した「ga:13012476」についてですが
v2の時はEntries()などで比較的容易に取得できましたけど。。。
- Management management = analytics.management();
-
- Accounts accounts = management.accounts().list().execute();
- List<Account> accountList = accounts.getItems();
- Account account = accountList.get(0);
- String accountId = account.getId();
-
- Webproperties prop = management.webproperties().list(accountId)
- .execute();
- Webproperty webproperty = prop.getItems().get(0);
- String webId = webproperty.getId();
-
- Profiles profiles = management.profiles().list(accountId, webId)
- .execute();
- Profile profile = profiles.getItems().get(0);
- String profileId = profile.getId();
-
- System.out.println("accountId:" + accountId);
- System.out.println("webId:" + webId);
- System.out.println("profileId:" + profileId);
Management management = analytics.management();
Accounts accounts = management.accounts().list().execute();
List<Account> accountList = accounts.getItems();
Account account = accountList.get(0);
String accountId = account.getId();
Webproperties prop = management.webproperties().list(accountId)
.execute();
Webproperty webproperty = prop.getItems().get(0);
String webId = webproperty.getId();
Profiles profiles = management.profiles().list(accountId, webId)
.execute();
Profile profile = profiles.getItems().get(0);
String profileId = profile.getId();
System.out.println("accountId:" + accountId);
System.out.println("webId:" + webId);
System.out.println("profileId:" + profileId);
わかりやすくすべてのデータについて、itemsの1件目を取得してます。
Accountはマルチアカウント用なのかな、、、私の環境では1件でした。
WebPropertyは解析しているサイト数が出てきました。
その中からプロファイルを取得する感じですね。
少しAnalytics自体のデータ構造がわかってないのでこれで正しいのか不明です。
execute()時にAPIを発行しているはずなので、、、うーんって感じ。
感想
なんかライブラリが多すぎて少し引きました><。
実際実装する際にはライブラリではなく、RESTfulアクセスすると思います。
なぜかというと、個人(セッション)に対して何を残せば良いかがわかりにくく
アクセスなどが隠蔽されているので何か使いにくいというか、、、って感じです。
※いやこのコード位の事やるにはいいんですけどね。
まぁJSONからデータのオブジェクト作ったりするのが大変だったりもするんですけど。