使用Java IntelliJ IDEA的YouTube分析API中出现空指针异常?

使用Java IntelliJ IDEA的YouTube分析API中出现空指针异常?,java,Java,使用Java IntelliJ IDEA的YouTube分析API中出现空指针异常? 能给我一个建议吗 Throwable: null java.lang.NullPointerException at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191) at com.google.api.client.util.Preconditio

使用Java IntelliJ IDEA的YouTube分析API中出现空指针异常? 能给我一个建议吗

Throwable: null
java.lang.NullPointerException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:96)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at com.google.api.services.samples.youtube.cmdline.analytics.YouTubeAnalyticsReports.main(YouTubeAnalyticsReports.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
这是Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.api.services.samples.youtube.cmdline</groupId>
<artifactId>samples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>youtube-api-cmdline-samples</name>
<url>http://maven.apache.org</url>

<properties>
    <project.youtube.version>v3-rev107-1.18.0-rc</project.youtube.version>
    <project.youtube.analytics.version>v1-rev24-1.17.0-rc</project.youtube.analytics.version>
    <project.http.version>1.18.0-rc</project.http.version>
    <project.oauth.version>1.18.0-rc</project.oauth.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<repositories>
    <repository>
        <id>google-api-services</id>
        <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
    </repository>
</repositories>

<dependencies>

    <!-- YouTube Data V3 support -->
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-youtube</artifactId>
        <version>${project.youtube.version}</version>
    </dependency>

    <!-- Required for any code that makes calls to the Google Analytics API -->
    <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-youtubeAnalytics</artifactId>
        <version>${project.youtube.analytics.version}</version>
    </dependency>

    <!-- This dependency is only used for the Topics API sample, which requires the Jackson JSON parser -->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.4</version>
    </dependency>

    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson2</artifactId>
        <version>${project.http.version}</version>
    </dependency>

    <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>${project.oauth.version}</version>
    </dependency>

    <dependency>
        <groupId>com.google.collections</groupId>
        <artifactId>google-collections</artifactId>
        <version>1.0</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <!-- Forces Maven to use Java 1.6 -->
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument></compilerArgument>
            </configuration>
        </plugin>
    </plugins>
</build>

4.0.0
com.google.api.services.samples.youtube.cmdline
样品
0.0.1-快照
罐子
youtube api cmdline示例
http://maven.apache.org
v3-rev107-1.18.0-rc
v1-rev24-1.17.0-rc
1.18.0-rc
1.18.0-rc
UTF-8
谷歌api服务
http://google-api-client-libraries.appspot.com/mavenrepo
com.google.api
谷歌api服务youtube
${project.youtube.version}
com.google.api
谷歌api服务YouTubeAnytics
${project.youtube.analytics.version}
org.codehaus.jackson
杰克逊地图绘制者
1.9.4
com.google.http-client
google-http-client-jackson2
${project.http.version}
com.google.oauth-client
谷歌oauth客户端jetty
${project.oauth.version}
com.google.collections
谷歌收藏
1
maven编译器插件
2.3.2
1.6
1.6

我需要在Java IntelliJ IDEA中使用YouTube分析API为YouTube视频生成报告

如何解决这个异常你能请任何人帮你吗?这对我会有帮助的

Report.java

package com.google.api.services.samples.youtube.cmdline.analytics;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtubeAnalytics.YouTubeAnalytics;
import com.google.api.services.youtubeAnalytics.model.ResultTable;
import com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.List;

public class YouTubeAnalyticsReports {
/**
 * Define a global instance of the HTTP transport.
 */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

/**
 * Define a global instance of the JSON factory.
 */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

/**
 * Define a global instance of a Youtube object, which will be used
 * to make YouTube Data API requests.
 */
private static YouTube youtube;

/**
 * Define a global instance of a YoutubeAnalytics object, which will be
 * used to make YouTube Analytics API requests.
 */
private static YouTubeAnalytics analytics;

/**
 * This code authorizes the user, uses the YouTube Data API to retrieve
 * information about the user's YouTube channel, and then fetches and
 * prints statistics for the user's channel using the YouTube Analytics API.
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    // These scopes are required to access information about the
    // authenticated user's YouTube channel as well as Analytics
    // data for that channel.
    List<String> scopes = Lists.newArrayList(
            "https://www.googleapis.com/auth/yt-analytics.readonly",
            "https://www.googleapis.com/auth/youtube.readonly"
    );

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "analyticsreports");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

        // This object is used to make YouTube Analytics API requests.
        analytics = new YouTubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("youtube-analytics-api-report-example")
                .build();

        // Construct a request to retrieve the current user's channel ID.
        YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet");
        channelRequest.setMine(true);
        channelRequest.setFields("items(id,snippet/title)");
        ChannelListResponse channels = channelRequest.execute();

        // List channels associated with the user.
        List<Channel> listOfChannels = channels.getItems();

        // The user's default channel is the first item in the list.
        Channel defaultChannel = listOfChannels.get(0);
        String channelId = defaultChannel.getId();

        PrintStream writer = System.out;
        if (channelId == null) {
            writer.println("No channel found.");
        } else {
            writer.println("Default Channel: " + defaultChannel.getSnippet().getTitle() +
                    " ( " + channelId + " )\n");

            printData(writer, "Views Over Time.", executeViewsOverTimeQuery(analytics, channelId));
            printData(writer, "Top Videos", executeTopVideosQuery(analytics, channelId));
            printData(writer, "Demographics", executeDemographicsQuery(analytics, channelId));
        }
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

/**
 * Retrieve the views and unique viewers per day for the channel.
 *
 * @param analytics The service object used to access the Analytics API.
 * @param id        The channel ID from which to retrieve data.
 * @return The API response.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeViewsOverTimeQuery(YouTubeAnalytics analytics,
                                                     String id) throws IOException {

    return analytics.reports()
            .query("channel==" + id,     // channel id
                    "2012-01-01",         // Start date.
                    "2012-01-14",         // End date.
                    "views,uniques")      // Metrics.
            .setDimensions("day")
            .setSort("day")
            .execute();
}

/**
 * Retrieve the channel's 10 most viewed videos in descending order.
 *
 * @param analytics the analytics service object used to access the API.
 * @param id        the string id from which to retrieve data.
 * @return the response from the API.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeTopVideosQuery(YouTubeAnalytics analytics,
                                                 String id) throws IOException {

    return analytics.reports()
            .query("channel==" + id,                          // channel id
                    "2012-01-01",                              // Start date.
                    "2012-08-14",                              // End date.
                    "views,subscribersGained,subscribersLost") // Metrics.
            .setDimensions("video")
            .setSort("-views")
            .setMaxResults(10)
            .execute();
}

/**
 * Retrieve the demographics report for the channel.
 *
 * @param analytics the analytics service object used to access the API.
 * @param id        the string id from which to retrieve data.
 * @return the response from the API.
 * @throws IOException if an API error occurred.
 */
private static ResultTable executeDemographicsQuery(YouTubeAnalytics analytics,
                                                    String id) throws IOException {
    return analytics.reports()
            .query("channel==" + id,     // channel id
                    "2007-01-01",         // Start date.
                    "2012-08-14",         // End date.
                    "viewerPercentage")   // Metrics.
            .setDimensions("ageGroup,gender")
            .setSort("-viewerPercentage")
            .execute();
}

/**
 * Prints the API response. The channel name is printed along with
 * each column name and all the data in the rows.
 *
 * @param writer  stream to output to
 * @param title   title of the report
 * @param results data returned from the API.
 */
private static void printData(PrintStream writer, String title, ResultTable results) {
    writer.println("Report: " + title);
    if (results.getRows() == null || results.getRows().isEmpty()) {
        writer.println("No results Found.");
    } else {

        // Print column headers.
        for (ColumnHeaders header : results.getColumnHeaders()) {
            writer.printf("%30s", header.getName());
        }
        writer.println();

        // Print actual data.
        for (List<Object> row : results.getRows()) {
            for (int colNum = 0; colNum < results.getColumnHeaders().size(); colNum++) {
                ColumnHeaders header = results.getColumnHeaders().get(colNum);
                Object column = row.get(colNum);
                if ("INTEGER".equals(header.getUnknownKeys().get("dataType"))) {
                    long l = ((BigDecimal) column).longValue();
                    writer.printf("%30d", l);
                } else if ("FLOAT".equals(header.getUnknownKeys().get("dataType"))) {
                    writer.printf("%30f", column);
                } else if ("STRING".equals(header.getUnknownKeys().get("dataType"))) {
                    writer.printf("%30s", column);
                } else {
                    // default output.
                    writer.printf("%30s", column);
                }
            }
            writer.println();
        }
        writer.println();
    }
}
package com.google.api.services.samples.youtube.cmdline.analytics;
导入com.google.api.client.auth.oauth2.Credential;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.http.javanet.NetHttpTransport;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.json.jackson2.JacksonFactory;
导入com.google.api.services.samples.youtube.cmdline.Auth;
导入com.google.api.services.youtube.youtube;
导入com.google.api.services.youtube.model.Channel;
导入com.google.api.services.youtube.model.ChannelListResponse;
导入com.google.api.services.youtubeAnalytics.youtubeAnalytics;
导入com.google.api.services.youtubeAnalytics.model.resultable;
导入com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders;
导入com.google.common.collect.list;
导入java.io.IOException;
导入java.io.PrintStream;
导入java.math.BigDecimal;
导入java.util.List;
公共类YouTube分析报告{
/**
*定义HTTP传输的全局实例。
*/
私有静态最终HttpTransport HTTP_TRANSPORT=new NetHttpTransport();
/**
*定义JSON工厂的全局实例。
*/
私有静态最终JsonFactory JSON_FACTORY=new JacksonFactory();
/**
*定义将要使用的Youtube对象的全局实例
*发出YouTube数据API请求。
*/
私有静态YouTube YouTube;
/**
*定义YoutubeAnalytics对象的全局实例,该实例将
*用于发出YouTube分析API请求。
*/
私有静态YouTubeanAnalytics分析;
/**
*此代码授权用户,使用YouTube数据API检索
*有关用户的YouTube频道的信息,然后获取和
*使用YouTube分析API打印用户频道的统计信息。
*
*@param args命令行args(未使用)。
*/
公共静态void main(字符串[]args){
//这些作用域是访问有关
//已验证用户的YouTube频道以及分析
//该频道的数据。
列表范围=Lists.newArrayList(
"https://www.googleapis.com/auth/yt-analytics.readonly",
"https://www.googleapis.com/auth/youtube.readonly"
);
试一试{
//批准请求。
凭证=授权(作用域,“分析报告”);
//此对象用于发出YouTube数据API请求。
youtube=new youtube.Builder(HTTP_传输、JSON_工厂、凭证)
.setApplicationName(“youtube分析api报告示例”)
.build();
//此对象用于发出YouTube分析API请求。
analytics=new YouTubeAnalytics.Builder(HTTP_传输、JSON_工厂、凭证)
.setApplicationName(“youtube分析api报告示例”)
.build();
//构造一个请求以检索当前用户的通道ID。
YouTube.Channels.List channelRequest=YouTube.Channels().List(“id,snippet”);
channelRequest.setMine(true);
channelRequest.setFields(“项目(id、代码段/标题)”);
ChannelListResponse channels=channelRequest.execute();
//列出与用户关联的频道。
List ListofChannel=channels.getItems();
//用户的默认频道是列表中的第一项。
Channel defaultChannel=ListofChannel.get(0);
字符串channelId=defaultChannel.getId();
PrintStream writer=System.out;
if(channelId==null){
writer.println(“未找到频道”);
}否则{
writer.println(“默认通道:+defaultChannel.getSnippet().getTitle())+
“(“+channelId+”)\n”);
printData(作者,“随时间变化的视图”,executeViewsOverTimeQuery(分析,channelId));
printData(编剧,“顶级视频”,executeTopVideosQuery(分析,渠道ID));
printData(作者,“人口统计”,执行的人口统计(分析,渠道ID));
}
}捕获(IOE异常){
System.err.println(“IOException:+e.getMessage());
e、 printStackTrace();
}捕获(可丢弃的t){
System.err.println(“Throwable:+t.getMessage());
t、 printStackTrace();
}
}
/**
*检索频道每天的视图和唯一查看器。
*
*@param analytics用于访问分析的服务对象
<repositories>
    <repository>
        <id>google-api-services</id>
        <url>http://mavenrepo.google-api-java-client.googlecode.com/hg</url>
    </repository>
    <repository>
        <id>google-api-services</id>
        <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
    </repository>
</repositories>