代码之家  ›  专栏  ›  技术社区  ›  yankee

使用java youtube API恢复上传

  •  1
  • yankee  · 技术社区  · 13 年前

    我正在尝试使用Java API将视频上传到YouTube,如下所示:

        private Video uploadVideo(final YouTube youtube, final Video video, final InputStreamContent mediaContent)
                throws IOException {
            YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status", video, mediaContent);
    
            MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
            uploader.setDirectUploadEnabled(false);
            uploader.setProgressListener(progressListener);
            return videoInsert.execute();
        }
    }
    

    我的互联网连接缓慢且不稳定,如果我能恢复上传到工作中,那将非常有帮助。文件 here 和 here 似乎向我建议“setDirectUploadEnabled(false)”应该完全做到这一点。好显然不是。

    如果我的互联网连接中断,会引发IOException,并且没有自动上传恢复。

    如何恢复上传?

    1 回复  |  直到 11 年前
        1
  •  2
  •   yankee    13 年前

    文件编制似乎落后于实际实施。幸运的是,它是开源的,你可以简单地阅读源代码来找到解决方案。 这是关于1.16-rc版本 :

    如果在上传过程中发生IOException com.google.api.client.googleapis.media.MediaUploadErrorHandler 用于处理异常。此处理程序还负责恢复上载,但只有在HTTP请求中注册的另一个异常处理程序成功处理IOException时,它才会这样做。这一前提条件在未来可能会发生变化,因为当前版本中的注释表明:

    // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if I/O
    // exception was handled, or call it regardless
    

    由于默认io异常处理程序为null,因此必须显式设置一个异常处理程序。这可以在构建 YouTube -对象:

    示例源代码 here 初始化 YouTube 对象如下:

    youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-uploadvideo-sample").build();
    

    要使此示例生效,请将行修改为:

    youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {          
      @Override
      public void initialize(HttpRequest request) throws IOException {
        credential.initialize(request);
        request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
      }
    });
    

    这个 HTTPRequestInitializer 每次 HTTPRequest 构造并设置IOExceptionHandler。从那时起 MediaUploadErrorHandler 将首先将异常传递给 HttpBackOffIOExceptionHandler 其可以在允许重试之前休眠一段时间。之后 媒体上传错误处理程序 将尝试继续上载。

    请注意 credential 是一个 HttpRequestInitializer 同样,您需要执行这两个初始化程序。因此,在我的例子中, 资质 在我添加的Initializer中调用。

    推荐文章