1

我正在尝试使用 Google Drive API 发送 HTTP 多部分请求以在 Google Drive 中插入文件。

我正在关注以下链接:分段上传

但是,我得到一个Bad request error.

下面是我使用上面的文档链接创建的请求字符串:

    String content = '\r\n--' + boundary + '\r\n';
    content +='Content-Type: '+'application/json; charset=UTF-8'+'\r\n\r\n';
    content +='{' + '\r\n';
    content +='"title": "My File"'+'\r\n';
    content +='}'+'\r\n\r\n';
    content += '--'+boundary + '\r\n';
    content +='Content-Type: '+'text/plain'+'\r\n';
    content += EncodingUtil.base64Encode(b)+'\r\n';
    content += '-'+boundary+'-\r\n';

请有人能告诉我我在这里缺少什么吗?

4

2 回答 2

1

我也有这个问题,在尝试了一些改变之后,我终于找到了一个可行的例子:

标题:

POST /upload/drive/v2/files?uploadType=multipart&access_token=ya29.CjAmA2j6eonCiROaNum-V1cWdFVH2vXpNiXAsXK6iLPu7K54tD4uNsmH-eEycMcnaBE HTTP/1.1
Host: www.googleapis.com
Accept: */*
Content-Type: multipart/related; boundary="foo_bar_baz"
Content-Length: 150

记得在 Content-Type 字段中添加 boundary="foo_bar_baz"

身体 :

--foo_bar_baz
Content-Type: application/json; charset=UTF-8

{
    "title": "My File"
}

--foo_bar_baz
Content-Type: text/txt

JPEG data
--foo_bar_baz--
于 2016-07-20T07:45:14.610 回答
1

我也遇到了麻烦,但是如果您查看 github 上的 google drive API 的代码: Github Drive API

请求参数接受一个媒体对象,它可以有一个 body 和 mimeType。

我正在使用服务帐户,这使您可以将文件直接上传到驱动器。

 auth.getApplicationDefault(function(err, authClient) {
  if (err) {
    console.log('Authentication failed because of ', err);
    return;
  }
  if (authClient.createScopedRequired && authClient.createScopedRequired()) {
   var scopes = ['https://www.googleapis.com/auth/drive'];
   authClient = authClient.createScoped(scopes);
  }
  var request = {
  project: "YOUR_PROJECT",
  auth: authClient,
  resource: {
    parents: ['blah']
  },
  media: {
    body: 'hi',
    mimeType: 'text/plain'
  }
 };
 drive.files.create(request, function(err, result) {
    if (err) {
      console.log(err);
    } else {
      console.log(result);
    }
  });
});
于 2016-12-01T20:57:12.407 回答