android - 对于文件> 1mb,驱动器REST API返回400

标签 android rest gradle groovy google-drive-api

我已经阅读了许多类似的问题,但没有找到可接受的答案。

我正在编写简单的驱动器上传任务,供gradle成功构建后上传android .apk文件。我不使用Drive Java API,仅使用REST请求。

此任务检索 token :

task getToken << {
  def keyStoreFile = file("SomeProject-PrivateKey.p12")
  def keyStorePass = "notasecret"
  def serviceAccountEmail = "someserviceemail@someproject.iam.gserviceaccount.com"

  def keyStore = java.security.KeyStore.getInstance("PKCS12")
  keyStore.load(keyStoreFile.newInputStream(), keyStorePass.toCharArray())
  def privateKey = keyStore.getKey(keyStore.aliases().nextElement(), keyStorePass.toCharArray())

  def JWTHeader = '{"alg":"RS256","typ":"JWT"}'
  def JWTClaimSet = '{\n' +
        '  "iss":' + serviceAccountEmail + ',\n' +
        '  "scope":"https://www.googleapis.com/auth/drive",\n' +
        '  "aud":"https://www.googleapis.com/oauth2/v4/token",\n' +
        '  "exp":' + (System.currentTimeSeconds() + 5 * 60) + ',\n' +   // + 5 minutes
        '  "iat":' + System.currentTimeSeconds() + '\n' +
        '}'
  def JWT = new String(Base64.urlEncoder.encode(JWTHeader.bytes)) +
        '.' + new String(Base64.urlEncoder.encode(JWTClaimSet.bytes))

  def signature = java.security.Signature.getInstance("SHA256withRSA")
  signature.initSign(privateKey)
  signature.update(JWT.bytes)
  JWT += '.' + new String(Base64.urlEncoder.encode(signature.sign()))

  System.out.print "assertion: " + JWT + "\n"

  def authUrl = new URL("https://www.googleapis.com/oauth2/v4/token")
  HttpURLConnection auth = authUrl.openConnection()
  auth.setRequestMethod("POST")
  auth.setRequestProperty("Host", "www.googleapis.com")
  auth.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
  auth.setDoOutput(true)
  def body = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer' +
        '&assertion=' + JWT
  auth.outputStream.write(body.bytes)
  def reader = new BufferedReader(new InputStreamReader(auth.inputStream))

  StringBuilder sb = new StringBuilder()
  for (int c; (c = reader.read()) >= 0;)
    sb.append((char) c)
  System.out.println(sb.toString())
}

然后将此文件上传到一些公用文件夹或与serviceemail@someproject.iam.gserviceaccount.com共享的文件夹中:
task uploadToDrive << {
  File apk = file("test1.txt")
  //    File apk = file("test2.apk")
  def url = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart");

  HttpURLConnection drive = url.openConnection();
  drive.setRequestMethod("POST")
  drive.setRequestProperty("Host", "www.googleapis.com")
  drive.setRequestProperty("Authorization", "Bearer " + "ya29.ElnDA_idxn6dL4cji6Oh3dQbdCaMGtGfmIMwIDa4yrEgiL9G8I6qHeSoCNUwcfYESZiLBBaymYLWJQBuTgypqyOy_YVUNpwyd2Gf8rYLgAsSksNnruygoFBS9g")
  drive.setRequestProperty("Content-Type", "multipart/related; boundary=foo_bar_baz")

  String body = '\n' +
        '--foo_bar_baz\n' +
        'Content-Type: application/json; charset=UTF-8\n\n' +
        '{\n' +
        '  "name": "TEST",\n' +
        '  "parents": [ "0BzkpQECQo2d2SEo5OTd4RHpnOFE" ]\n' +
        '}\n\n' +
        '--foo_bar_baz\n' +
        'Content-Type: application/octet-stream\n\n'
  String end = '--foo_bar_baz--'

  drive.setFixedLengthStreamingMode(body.bytes.length + apk.length() + end.bytes.length)     // Content Length

  drive.setDoOutput(true)
  drive.setDoInput(true)
  drive.outputStream.write(body.bytes)
  apk.withInputStream { is ->
    def buffer = new byte[1024];
    int len;
    while ((len = is.read(buffer)) != -1) {
        drive.outputStream.write(buffer, 0, len);
    }
  }
  drive.outputStream.write(end.bytes)

  def reader = new BufferedReader(new InputStreamReader(drive.inputStream))
  StringBuilder sb = new StringBuilder()
  for (int c; (c = reader.read()) >= 0;)
    sb.append((char) c);
  System.out.println(sb.toString())
}

对于小文件,它可以很好地工作!但是,当我尝试上传真正的.apk文件或什至〜1Mb图像gradle失败时:

Execution failed for task ':uploadToDrive'. Server returned HTTP response code: 400 for URL: https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart



有任何想法吗?

最佳答案

并不是真正的答案(为什么是400?),但是它可以解决问题。
感谢Mr.Rebotpinoyyid

可恢复的上载示例,其中适用于大文件:

task uploadResumable << {
  File apk = file("dog.jpg")
  def url = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");

  HttpURLConnection drive = url.openConnection();
  drive.setRequestMethod("POST")
  drive.setRequestProperty("Host", "www.googleapis.com")
  drive.setRequestProperty("Authorization", "Bearer " + "ya29.ElnDA_idxn6dL4cji6Oh3dQbdCaMGtGfmIMwIDa4yrEgiL9G8I6qHeSoCNUwcfYESZiLBBaymYLWJQBuTgypqyOy_YVUNpwyd2Gf8rYLgAsSksNnruygoFBS9g")
  drive.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
  drive.setRequestProperty("X-Upload-Content-Type", "image/jpeg")

  String body = '\n' +
        '{\n' +
        '  "name": "DOGresum",\n' +
        '  "parents": [ "0BzkpQECQo2d2SEo5OTd4RHpnOFE" ]\n' +
        '}\n\n';

  drive.setFixedLengthStreamingMode(body.bytes.length)     // Content Length
  drive.setDoOutput(true)
  drive.setDoInput(true)
  drive.outputStream.write(body.bytes)

  // response header example:
  //      -> Location: [https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=AEnB...]
  // get "Location" header
  String loc = drive.getHeaderFields().get("Location")

  // trim '[' and ']' brackets and get URL query
  def query = new URL(loc[1..-2]).query

  // find upload_id value
  String uploadId;
  query.split('&').each {
    if (it.split('=')[0] == 'upload_id')
        uploadId = it.split('=')[1]
  }

  // start new upload
  def url2 = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=" + uploadId);
  HttpURLConnection drive2 = url2.openConnection()
  drive2.setRequestMethod('POST')
  drive2.setRequestProperty("Content-Type", "image/jpeg")
  drive2.setFixedLengthStreamingMode(apk.bytes.length)     // Content Length
  drive2.setDoOutput true
  drive2.setDoInput true
  drive2.outputStream.write apk.bytes
}

关于android - 对于文件> 1mb,驱动器REST API返回400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379958/

相关文章:

android - 在 Android 中管理构建标志

java - 为什么返回类型不满足方法签名?

node.js - 如何通过REST接口(interface)从Oozie获取通知?

java - Gradle 不下载测试依赖项

gradle - 是否可以从同一个子项目并行运行两个独立的 gradle 任务?

android - 在 Android Studio 中出现渲染问题, View 不显示

android - 是否可以在 fragment 中手动调用 onCreateView?

objective-c - 在 REST Api 中建模对象继承

java - 将base64中的图像从rest服务返回到img src标签

android - react 原生创建一个 android 模块 .gitignore 文件