如何使用Java REST Client API部分下载Google驱动器文件? [英] How to partial download google drive files using java REST Client API?

查看:68
本文介绍了如何使用Java REST Client API部分下载Google驱动器文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的示例代码(Drive Java REST API V3),我正在尝试从Google驱动器下载文件的一部分.

Using the sample code (Drive Java REST API V3) below, I am trying to download a portion of a file from google drive.

Drive.Revisions.Get get = service.revisions().get(fileId, revisionId)
            .setFields(FilterConstants.OBJECT_REVISION);

MediaHttpDownloader downloader = get.getMediaHttpDownloader();
downloader.setContentRange(fromByte, toByte);

inputStream = get.executeMediaAsInputStream();

但这对我不起作用.有人可以帮我解决这个问题吗?

But this is not working for me. Can someone help me how to resolve this issue?

推荐答案

以下代码对我有用.诀窍是正确设置Range标头

The following code works for me. The trick was to set Range header correctly

private byte[] getBytes(Drive drive, String downloadUrl, long position, int byteCount) {
    byte[] receivedByteArray = null;
    if (downloadUrl != null && downloadUrl.length() > 0) {
        try {
            com.google.api.client.http.HttpRequest httpRequestGet = drive.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl));
            httpRequestGet.getHeaders().setRange("bytes=" + position + "-" + (position + byteCount - 1));
            com.google.api.client.http.HttpResponse response = httpRequestGet.execute();
            InputStream is = response.getContent();
            receivedByteArray = IOUtils.toByteArray(is);
            response.disconnect();
            System.out.println("google-http-client-1.18.0-rc response: [" + position + ", " + (position + receivedByteArray.length - 1) + "]");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return receivedByteArray;
}

这篇关于如何使用Java REST Client API部分下载Google驱动器文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆