空指针异常在Youtube API中

huangapple go评论70阅读模式
英文:

NullPointerExceptions in Youtube API

问题

以下是您提供的代码的中文翻译部分:

我目前正在尝试学习如何使用YouTube API等内容但我遇到了一些NullPointerException错误我无法弄清楚原因...

我已经尝试了文档中能找到的一切但没有任何改变

private static final String APPLICATION_NAME = "API代码示例";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

/**
 * 创建已授权的凭据对象。
 *
 * @return 已授权的凭据对象。
 * @throws IOException
 */
public static Credential authorize(final NetHttpTransport httpTransport) throws IOException {
    // 加载客户端秘钥。
    InputStream in = CreateBroadcast.class.getResourceAsStream(CLIENT_SECRETS);
    GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
    // 构建流程并触发用户授权请求。
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
        .build();
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    return credential;
}

/**
 * 构建并返回已授权的API客户端服务。
 *
 * @return 已授权的API客户端服务
 * @throws GeneralSecurityException, IOException
 */
public static YouTube getService() throws GeneralSecurityException, IOException {
    final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    Credential credential = authorize(httpTransport);
    return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME)
        .build();
}

/**
 * 调用函数以创建API服务对象。定义并执行API请求。打印API响应。
 *
 * @throws GeneralSecurityException, IOException, GoogleJsonResponseException
 */
public static void main(String[] args)
    throws GeneralSecurityException, IOException, GoogleJsonResponseException {
    YouTube youtubeService = getService();
    
    // 定义LiveBroadcast对象,将上传为请求主体。
    LiveBroadcast liveBroadcast = new LiveBroadcast();
    
    // 将contentDetails对象属性添加到LiveBroadcast对象。
    LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
    contentDetails.setEnableClosedCaptions(true);
    contentDetails.setEnableContentEncryption(true);
    contentDetails.setEnableDvr(true);
    contentDetails.setEnableEmbed(true);
    contentDetails.setRecordFromStart(true);
    contentDetails.setStartWithSlate(true);
    liveBroadcast.setContentDetails(contentDetails);
    
    // 将snippet对象属性添加到LiveBroadcast对象。
    LiveBroadcastSnippet snippet = new LiveBroadcastSnippet();
    snippet.setScheduledStartTime(new DateTime("2024-01-30T00:00:00.000Z"));
    snippet.setTitle("测试广播");
    liveBroadcast.setSnippet(snippet);
    
    // 将status对象属性添加到LiveBroadcast对象。
    LiveBroadcastStatus status = new LiveBroadcastStatus();
    status.setPrivacyStatus("unlisted");
    liveBroadcast.setStatus(status);

    // 定义并执行API请求
    YouTube.LiveBroadcasts.Insert request = youtubeService.liveBroadcasts()
        .insert("snippet,contentDetails,status", liveBroadcast);
    LiveBroadcast response = request.execute();
    System.out.println(response);
}

这是您提供的代码的翻译。如果您还需要关于错误的帮助,请随时告诉我。

英文:

I am currently trying to learn how to use the Youtube APIs and stuff, but I am getting a few NullPointerException Errors, and I just cant figure out why...

I already tried everything I could find in the Documentation, but nothing changed.

private static final String APPLICATION_NAME = "API code samples";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/**
* Create an authorized Credential object.
*
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize(final NetHttpTransport httpTransport) throws IOException {
// Load client secrets.
InputStream in = CreateBroadcast.class.getResourceAsStream(CLIENT_SECRETS);
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets, SCOPES)
.build();
Credential credential =
new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
/**
* Build and return an authorized API client service.
*
* @return an authorized API client service
* @throws GeneralSecurityException, IOException
*/
public static YouTube getService() throws GeneralSecurityException, IOException {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
Credential credential = authorize(httpTransport);
return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
/**
* Call function to create API service object. Define and
* execute API request. Print API response.
*
* @throws GeneralSecurityException, IOException, GoogleJsonResponseException
*/
public static void main(String[] args)
throws GeneralSecurityException, IOException, GoogleJsonResponseException {
YouTube youtubeService = getService();
// Define the LiveBroadcast object, which will be uploaded as the request body.
LiveBroadcast liveBroadcast = new LiveBroadcast();
// Add the contentDetails object property to the LiveBroadcast object.
LiveBroadcastContentDetails contentDetails = new LiveBroadcastContentDetails();
contentDetails.setEnableClosedCaptions(true);
contentDetails.setEnableContentEncryption(true);
contentDetails.setEnableDvr(true);
contentDetails.setEnableEmbed(true);
contentDetails.setRecordFromStart(true);
contentDetails.setStartWithSlate(true);
liveBroadcast.setContentDetails(contentDetails);
// Add the snippet object property to the LiveBroadcast object.
LiveBroadcastSnippet snippet = new LiveBroadcastSnippet();
snippet.setScheduledStartTime(new DateTime("2024-01-30T00:00:00.000Z"));
snippet.setTitle("Test broadcast");
liveBroadcast.setSnippet(snippet);
// Add the status object property to the LiveBroadcast object.
LiveBroadcastStatus status = new LiveBroadcastStatus();
status.setPrivacyStatus("unlisted");
liveBroadcast.setStatus(status);
// Define and execute the API request
YouTube.LiveBroadcasts.Insert request = youtubeService.liveBroadcasts()
.insert("snippet,contentDetails,status", liveBroadcast);
LiveBroadcast response = request.execute();
System.out.println(response);
}

And these are the Errors I keep getting:

Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Reader.java:167)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at com.google.api.services.samples.youtube.cmdline.live.CreateBroadcast.authorize(CreateBroadcast.java:47)
at com.google.api.services.samples.youtube.cmdline.live.CreateBroadcast.getService(CreateBroadcast.java:65)
at com.google.api.services.samples.youtube.cmdline.live.CreateBroadcast.main(CreateBroadcast.java:79)

I am very sorry if this is a stupid question 空指针异常在Youtube API中
Thanks in advance, Thilo

答案1

得分: 0

很可能无法找到CLIENT_SECRETS资源,CreateBroadcast.class.getResourceAsStream(CLIENT_SECRETS)返回null。在接下来的代码行中,调用new InputStreamReader(in)并将其参数设为null会导致空指针异常(NPE)。

英文:

Most likely the CLIENT_SECRETS resource cannot be found and CreateBroadcast.class.getResourceAsStream(CLIENT_SECRETS) returns null. Call to new InputStreamReader(in) with null in the next line ends up with the NPE.

答案2

得分: 0

CreateBroadcast.class.getResourceAsStream(CLIENT_SECRETS) 返回null,正如文档所述,因为CLIENT_SECRETS不包含指向现有资源的资源URL。

需要注意的是,它必须是相对URL,而不是文件路径。相对URL意味着在所有平台上都带有斜杠(/)的路径。

如果您从.jar文件运行,您可以简单地验证.jar文件是否包含您请求的资源:

  • 如果CLIENT_SECRETS以斜杠开头,则相对于.jar文件的根目录。这意味着,如果CLIENT_SECRETS是"/config/secrets.txt",您的.jar文件需要包含config/secrets.txt条目。
  • 如果CLIENT_SECRETS不以斜杠开头,则相对于CreateBroadcast类的包。这意味着,如果CLIENT_SECRETS是"secrets.txt",.jar文件需要包含com/google/api/services/samples/youtube/cmdline/live/secrets.txt条目。

如果您未从.jar文件运行,则适用相同的规则,但您需要检查IDE添加的运行时类路径中的每个目录。许多IDE将符合Maven约定,并且将只使用项目中的target/classes子目录。

在所有情况下,如果CLIENT_SECRETS的值不是现有资源的路径,则getResourceAsStream方法将返回null。然后,您将该null传递给new InputStreamReader,这是您的异常原因。

英文:

This has nothing to do with the YouTube API.

CreateBroadcast.class.getResourceAsStream(CLIENT_SECRETS) is returning null, as the documentation states it will, because CLIENT_SECRETS does not contain a resource URL that points an existing resource.

Note that it must be a relative URL, not a file path. A relative URL means a path with a forward slashes (/), on all platforms.

If you are running from a .jar file, you can simply verify that the .jar file contains the resource you are requesting:

  • If CLIENT_SECRETS starts with an initial slash, it is relative to the root of the .jar file. Meaning, if CLIENT_SECRETS is "/config/secrets.txt", your .jar file needs to contain a config/secrets.txt entry.
  • If CLIENT_SECRETS does not start with an initial slash, it is relative to the package of the CreateBroadcast class. Meaning, if CLIENT_SECRETS is "secrets.txt", the .jar file needs to contain a com/google/api/services/samples/youtube/cmdline/live/secrets.txt entry.

If you are not running from a .jar file, the same rules apply, but you need to check every directory in your runtime classpath which was added by your IDE. Many IDEs will conform to Maven conventions and will just use the target/classes subdirectory in the project.

In all cases, if the value of CLIENT_SECRETS is not the path of an existing resource, the getResourceAsStream method returns null. You are then passing that null to new InputStreamReader, which is the cause of your exception.

huangapple
  • 本文由 发表于 2020年8月24日 04:23:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63551656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定