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



import com.google..client.auth.oauth2.Credential;
import com.google..client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google..client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google..client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google..client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google..client.googleapis.javanet.GoogleNetHttpTransport;
import com.google..client.http.HttpTransport;
import com.google..client.json.JsonFactory;
import com.google..client.json.jackson2.JacksonFactory;
import com.google..client.util.store.FileDataStoreFactory;
import com.google..services..v1.;
import com.google..services..v1.PeopleScopes;
import com.google..services..v1.model.ListConnectionsResponse;
import com.google..services.people.v1.model.Name;
import com.google..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  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..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..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下,放入后立刻搞定!

随机文章

道招网通过新浪微博官方机构认证
道招网通过新浪微博官方机构认证

oppo(欧珀)手机刷机图文教程
oppo(欧珀)手机刷机图文教程

sae-eclipse插件加新浪sae进行java项目开发
sae-eclipse插件加新浪sae进行java项目开发

百度搜索真坏啊
百度搜索真坏啊

安装运行angular2
安装运行angular2

相关文章

PHP版Google People API的坑
PHP版Google People API的坑

Eclipse不能自动编译java为class的解决办法
Eclipse不能自动编译java为class的解决办法

java 用math类的方法划近似圆
java 用math类的方法划近似圆

修改Eclipse ADT default debug keystore路径
修改Eclipse ADT default debug keystore路径

sae-eclipse插件加新浪sae进行java项目开发
sae-eclipse插件加新浪sae进行java项目开发

eclipse使用sqlexplorer插件(图文)
eclipse使用sqlexplorer插件(图文)

内容分享:道招
本文链接:eclipse报错”main” java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
道招声明:除特别标注或作者不详外,本站所有文章均为原创,转载请注明。欢迎共同关注互联网!