从Google API Resumable Update获取401 Unauthorized

时间:2012-04-14 13:12:29

标签: google-docs-api

我正在尝试将任意文件上传到Google文档到现有应用程序中。这在以前使用可恢复上传成为必需的。我正在使用Java客户端库。

应用程序通过两个步骤进行上传: - 获取文件的resourceId - 上传数据

要获取resourceId,我将上传0大小的文件(即Content-Length = 0)。我在可恢复的URL中传递?convert = false(即https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false)。

我将“application / octet-stream”作为内容类型传递。这似乎有用,虽然我确实得到了不同的资源ID - “file:...”resourceIds用于像图像这样的东西,但是“pdf:....”用于PDF的resourceIds。

第二步基于先前获得的resourceId构造URL并执行搜索(getEntry)。该网址采用https://docs.google.com/feeds/default/private/full/file%3A .....

的形式

找到条目后,ResumableGDataFileUploader用于使用正在上载的文件中的实际数据更新内容(0字节文件)。在构建ResumableGDataFileUploader实例时,此操作失败并显示401 Unauthorized响应。

我尝试过使用?convert = false以及?new-revision = true以及这两种方法同时进行。结果是一样的。

相关的代码:

MediaFileSource mediaFile = new MediaFileSource(
    tempFile, "application/octet-stream");

final ResumableGDataFileUploader.Builder builder = 
    new ResumableGDataFileUploader.Builder(client, mediaFile, documentListEntry);
builder.executor(MoreExecutors.sameThreadExecutor());
builder.requestType(ResumableGDataFileUploader.RequestType.UPDATE);

// This is where it fails
final ResumableGDataFileUploader resumableGDataFileUploader = builder.build();
resumableGDataFileUploader.start();

return tempFile.length();

“客户端”是DocsService的一个实例,配置为使用OAuth。它用于在给定的代码片段之前找到“documentListEntry”。

我必须明确指定请求类型,因为似乎客户端库代码包含导致“更新现有条目”案例的NullPointerException的错误。

我怀疑问题是在操作序列中(上传0字节文件以获取resourceId,然后使用实际文件更新),但我无法弄清楚它为什么不起作用。

请帮帮忙?

1 个答案:

答案 0 :(得分:3)

此代码段适用于使用OAuth 1.0和OAuth 2.0:

static void uploadDocument(DocsService client) throws IOException, ServiceException,
    InterruptedException {
  ExecutorService executor = Executors.newFixedThreadPool(10);

  File file = new File("<PATH/TO/FILE>");
  String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();

  DocumentListEntry documentEntry = new DocumentListEntry();
  documentEntry.setTitle(new PlainTextConstruct("<DOCUMENT TITLE>"));

  int DEFAULT_CHUNK_SIZE = 2 * 512 * 1024;
  ResumableGDataFileUploader.Builder builder =
      new ResumableGDataFileUploader.Builder(
          client,
          new URL(
              "https://docs.google.com/feeds/upload/create-session/default/private/full?convert=false"),
          new MediaFileSource(file, mimeType), documentEntry).title(file.getName())
          .requestType(RequestType.INSERT).chunkSize(DEFAULT_CHUNK_SIZE).executor(executor);

  ResumableGDataFileUploader uploader = builder.build();
  Future<ResponseMessage> msg = uploader.start();
  while (!uploader.isDone()) {
    try {
      Thread.sleep(100);
    } catch (InterruptedException ie) {
      throw ie; // rethrow
    }
  }

  DocumentListEntry uploadedEntry = uploader.getResponse(DocumentListEntry.class);
  // Print the document's ID.
  System.out.println(uploadedEntry.getId());
  System.out.println("Upload is done!");
}