今天学习了下谷歌的People API中的java版,具体步骤可以见,在这里第一次用了下gradle工具,用着还行。
用eclipse运行Quickstart.java
源码如下:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.people.v1.People;
import com.google.api.services.people.v1.PeopleScopes;
import com.google.api.services.people.v1.model.ListConnectionsResponse;
import com.google.api.services.people.v1.model.Name;
import com.google.api.services.people.v1.model.Person;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.Arrays;
import java.util.List;


public class PeopleQuickstart {
    /** Application name. */
    private static final String APPLICATION_NAME = "People API Java Quickstart";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty(
                "user.home"),
            ".credentials/people.googleapis.com-java-quickstart.json");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    /** Global instance of the scopes required by this quickstart.
    *
    * If modifying these scopes, delete your previously saved credentials
    * at ~/.credentials/people.googleapis.com-java-quickstart.json
    */
    private static final List<string> SCOPES = Arrays.asList(PeopleScopes.CONTACTS_READONLY);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    /**
    * Creates an authorized Credential object.
    * @return an authorized Credential object.
    * @throws IOException
    */
    public static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in = PeopleQuickstart.class.getResourceAsStream(
                "/client_secret.json");
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
                JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY)
                                                                                                                                       .setAccessType("offline")
                                                                                                                                       .build();

        // Credential credential = new AuthorizationCodeInstalledApp(
        // flow, new LocalServerReceiver()).authorize("user");
        Credential credential = new AuthorizationCodeInstalledApp(flow,
                new LocalServerReceiver.Builder().setPort(54771).build()).authorize(
                "user");
        System.out.println("Credentials saved to " +
            DATA_STORE_DIR.getAbsolutePath());

        return credential;
    }

    /**
    * Build and return an authorized People client service.
    * @return an authorized People client service
    * @throws IOException
    */
    public static People getPeopleService() throws IOException {
        Credential credential = authorize();

        return new People.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME)
                                                                           .build();
    }

    public static void main(String[] args) throws IOException {
        People service = getPeopleService();

        // Request 10 connections.
        ListConnectionsResponse response = service.people().connections()
                                                  .list("people/me")
                                                  .setPageSize(10).execute();

        // Print display name of connections if available.
        List<person> connections = response.getConnections();

        if ((connections != null) && (connections.size() > 0)) {
            for (Person person : connections) {
                List<name> names = person.getNames();

                if ((names != null) && (names.size() > 0)) {
                    System.out.println("Name: " +
                        person.getNames().get(0).getDisplayName());
                } else {
                    System.out.println("No names available for connection.");
                }
            }
        } else {
            System.out.println("No connections found.");
        }
    }
}

其中的81~82行,我改用了83~84行,因为LocalServerReceiver默认会用一个未被占用的随机的端口,经过改用后指定54711端口,那样才好在Google console里面的Credentials添加固定的Authorized redirect URIs,不用来回变了。
在代码运行时发现始终未弹出授权页面,看看了eclipse的控制台,发现错误信息如下:

六月 25, 2016 2:05:52 下午 com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
警告: unable to change permissions for everybody: E:.credentials\people.googleapis.com-java-quickstart.json
六月 25, 2016 2:05:52 下午 com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
警告: unable to change permissions for owner: E:.credentials\people.googleapis.com-java-quickstart.json
Exception in thread "main" java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
at com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver.getRedirectUri(LocalServerReceiver.java:98)
at com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp.authorize(AuthorizationCodeInstalledApp.java:76)
at PeopleQuickstart.authorize(PeopleQuickstart.java:82)
at PeopleQuickstart.getPeopleService(PeopleQuickstart.java:94)
at PeopleQuickstart.main(PeopleQuickstart.java:101)
Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 5 more

细看了一下,

Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest,

原来是该没有将tomcat的servlet-api.jar放到项目的JRE System Library下,放入后立刻搞定!

分类: Java

发表评论

电子邮件地址不会被公开。 必填项已用*标注