使用Drive SDK从Google云端硬盘下载文件时获取“302暂时移动”

时间:2013-03-29 07:10:17

标签: android google-drive-api

我试图在Android上的Google云端硬盘中下载文件,我正在关注https://developers.google.com/drive/manage-downloads#examples

中的示例
if (entry.getDownloadUrl() != null && entry.getDownloadUrl().length() > 0) 
{
    try
    {
        LogUtils.xi(this, "start opening url:", entry.getDownloadUrl());
        /* HttpRequestFactory: Thread-safe light-weight HTTP request factory layer on top of the HTTP */
        HttpResponse resp = manager.getDrive().getRequestFactory()
                        .buildGetRequest(new GenericUrl(entry.getDownloadUrl()))
                        .execute();
        return resp.getContent();
    } 
    catch (IOException e) 
    {
        LogUtils.xe(this, e.toString());
        e.printStackTrace();
        throw ExceptionUtils.getIOException("Can't open inputstream.", e);
    }
}
else 
{
    LogUtils.xw(this, "The file doesn't have any content stored on Drive.");
    return null;
}

但是得到错误302:有人知道这里发生了什么吗?

03-29 14:56:07.316 E/XXGoogleDrive(25539): [25566][DriveDLFutureTask] [getInputStream]com.google.api.client.http.HttpResponseException: **302 Moved Temporarily**
03-29 14:56:07.326 W/System.err(25539): com.google.api.client.http.HttpResponseException: 302 Moved Temporarily
03-29 14:56:07.326 W/System.err(25539):     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1062)

1 个答案:

答案 0 :(得分:0)

'暂时移动'是因为页面尝试重定向到用户身份验证页面或病毒扫描,以防文件大小超过25 MB

我通过使用带有'alt = media'查询参数的文件获取请求并且工作代码在下面

来实现它
private static byte[] getBytes(Drive drive, String accessToken, String fileId, long position, long byteCount) {
        byte[] receivedByteArray = null;
        String downloadUrl = "https://www.googleapis.com/drive/v3/files/" + fileId + "?alt=media&access_token="
                + accessToken;
        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;
    }