Google+ のJava版のデスクトップアプリのデモを動かす方法を見ていきましょう。 準備Eclipse3.5ですと、Maven Pluginがインストールしておくと楽この辺は、すべてgoogle-plus-java-cli-starterのReadme.txtに書いてある GEFプラグインを入れる。GEF Update Site - http://download.eclipse.org/tools/gef/updates/releasesもし、GEFを入れていないとMavenの前にGEFを入れておく でないと、Maven Install時にbundle org.eclipse.zest.core 0.0.0がないとかエラー出てはまる Mavenを入れるInstall New Softwareからm2clipse - http://m2eclipse.sonatype.org/sites/m2e をインストールする Mavenを設定するPreferenceのMavenから、Download Artifact Sources とDownload Artifact JavaDocをチェック Projectをインポートするgoogle-plus-java-cli-starterをインポートする。Mavenが必要なライブラリーをダウンロードしてくれる。 Google APIs Consoleの設定Google APIs ConsoleからGoogle+を有効にしたり、OAuth2.0 Client IDを作ったりするProduct Name入れて、この場合、デスクトップアプリなので Install Applicationをチェックして作成する。 API Keyなどを設定src/main/resources/config.properties のoauth_client_id = ID oauth_client_secret = SECRET google_api_key = KEY をGoogle APIs Consoleにて作成したOAuth2.0の値を入れる。 実行/google-plus-java-cli-starter/google-plus-java-cli-starter.launch を右クリックして RunAsからgoogle-plus-java-cli-starterを選ぶと実行開始認証 認証画面に飛ぶので、自分が作成したやつか確認してAcceptする Allow accessするとaccept token値が表示される。 ![]() この値をコンソールに入れる。 すると、自分のGoogle + Profile情報が表示される。(Google +に承認されてなくても) あとは、おまけで、某誰かのActivityが表示される。 ============== Get my Google+ profile ============== id: 113916029593854276051 name: Aki image url: https://lh3.googleusercontent.com/photo.jpg profile url: https://profiles.google.com/ ============== Listing My Activities ============== ============== Get an explicit public activity by ID ============== id: z12gtjhq3qn2xxl2o224exwiqruvtda0i url: https://plus.google.com/102817283354809142195/posts/F97fqZwJESL content: A picture... of a space ship... launched from earth 40 years ago. たまに、こういうエラー出るみたい { "error": { "errors": [ { "domain": "buzz", "reason": "backendError", "message": "Backend Error" } ], "code": 503, "message": "Backend Error" } } Exception in thread "main" com.google.api.client.http.HttpResponseException: 503 Service Unavailable at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:708) at com.google.api.services.plus.Plus$RemoteRequest.execute(Plus.java:487) at com.google.api.services.plus.Plus$Activities$List.executeUnparsed(Plus.java:188) at com.google.api.services.plus.Plus$Activities$List.execute(Plus.java:172) at Test2.listActivities(Test2.java:85) at Test2.main(Test2.java:43) 認証なしで動かすPublicなデーターを取るだけでなら認証は必要ありません。Sample.javaでも、getActivity()でやっているように、認証なしでunauthenticatedPlusだけでPublicな情報は取得できます。 だいたいこんな感じになります。 /* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.*; import java.io.IOException; /** * @author Yaniv Inbar * @author Tony Aiuto * @author Will Norris * @author Jenny Murphy */ public class Test2 { // private static Plus plus; private static Plus unauthenticatedPlus; private static String targetId="USER_ID"; public static void main(String[] args) throws IOException { Util.enableLogging(); try { setupTransport(); getProfile(); listActivities(); getActivity(); } catch (HttpResponseException e) { System.err.println(e.getResponse().parseAsString()); throw e; } } /** * Setup the transport for our API calls. */ private static void setupTransport() throws IOException { // Set up an unauthenticated client for requests that do not require authentication unauthenticatedPlus = new Plus(new NetHttpTransport(), new GsonFactory()); unauthenticatedPlus.setKey(Auth.GOOGLE_API_KEY); //Auth.authorize(); // Set up the request initializer in such a way that it can refresh access tokens // for us when they expire /* GoogleAccessProtectedResource requestInitializer = new GoogleAccessProtectedResource( Auth.getAccessToken(), new NetHttpTransport(), new GsonFactory(), Auth.CLIENT_ID, Auth.CLIENT_SECRET, Auth.getRefreshToken()); plus = new Plus(new NetHttpTransport(), requestInitializer, new GsonFactory()); */ } /** * List the public activities for the authenticated user * * @throws IOException if unable to call API */ private static void listActivities() throws IOException { header("Listing My Activities"); // Fetch the first page of activities ActivityFeed feed = unauthenticatedPlus.activities().list(targetId, "public").execute(); while (feed.getItems() != null) { System.out.println(); System.out.println("~~~~~~~~~~~~~~~~~~ New page of activities ~~~~~~~~~~~~~~~~~~"); System.out.println(); for (Activity activity : feed.getItems()) { show(activity); System.out.println(); System.out.println("------------------------------------------------------"); System.out.println(); activityId=activity.getId(); } // Fetch the next page Plus.Activities.List list = unauthenticatedPlus.activities().list(targetId, "public"); list.setPageToken(feed.getNextPageToken()); feed = list.execute(); } } static String activityId; /** * Get the most recent activity for the authenticated user. * * @throws IOException if unable to call API */ private static void getActivity() throws IOException { // A known public activity ID // String activityId = "z12gtjhq3qn2xxl2o224exwiqruvtda0i"; if(activityId != null) { // Now that we have an ID we can fetch the activity with that ID // We do not need to be authenticated to do this header("Get an explicit public activity by ID"); Activity activity = unauthenticatedPlus.activities().get(activityId).execute(); show(activity); } } /** * Get the profile for the authenticated user. * * @throws IOException if unable to call API */ private static void getProfile() throws IOException { header("Get my Google+ profile"); Person profile = unauthenticatedPlus.people().get(targetId).execute(); show(profile); } /** * Print the specified person on the command line. * * @param person the person to show */ private static void show(Person person) { System.out.println("id: " + person.getId()); System.out.println("name: " + person.getDisplayName()); System.out.println("image url: " + person.getImage().getUrl()); System.out.println("profile url: " + person.getUrl()); } /** * Print the specified activity on the command line. * * @param activity the activity to show */ private static void show(Activity activity) { System.out.println("id: " + activity.getId()); System.out.println("url: " + activity.getUrl()); System.out.println("content: " + activity.getPlusObject().getContent()); //activity.getPlusObject().get } private static void header(String name) { System.out.println(); System.out.println("============== " + name + " =============="); System.out.println(); } } |
Google+ >