You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PRDownloader从Google Drive下载文件,如何配置Bearer认证令牌?

给PRDownloader添加Google Drive认证头的非官方实现方案

嘿,我刚好折腾过类似的需求!PRDownloader官方确实没直接提供配置自定义请求头的入口,但它底层依赖OkHttp,我们可以通过替换它的默认OkHttpClient来注入Authorization认证头,这是个非常靠谱的非官方实现方式,亲测有效。

具体步骤如下:

1. 编写OkHttp拦截器,自动添加Bearer认证头

我们需要创建一个自定义的OkHttp Interceptor,它会在每个请求发出前自动加上Authorization: Bearer <ACCESS_TOKEN>头:

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class DriveAuthInterceptor implements Interceptor {
    // 用volatile保证多线程下的可见性,方便后续更新token
    private volatile String accessToken;

    public DriveAuthInterceptor(String initialToken) {
        this.accessToken = initialToken;
    }

    // 提供方法动态更新token(应对token过期的情况)
    public void updateAccessToken(String newToken) {
        this.accessToken = newToken;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        
        // 只有当token存在时才添加认证头,避免无意义的空头
        if (accessToken != null && !accessToken.trim().isEmpty()) {
            Request authenticatedRequest = originalRequest.newBuilder()
                    .header("Authorization", "Bearer " + accessToken)
                    .build();
            return chain.proceed(authenticatedRequest);
        }
        
        return chain.proceed(originalRequest);
    }
}

2. 初始化PRDownloader时注入自定义OkHttpClient

在App启动阶段(比如Application的onCreate方法里),初始化PRDownloader的时候,替换它的默认OkHttpClient,把上面的拦截器加进去:

import com.downloader.PRDownloader;
import com.downloader.PRDownloaderConfig;
import okhttp3.OkHttpClient;

// 先实例化我们的认证拦截器
DriveAuthInterceptor authInterceptor = new DriveAuthInterceptor("你的Google Drive访问令牌");

// 构建带拦截器的OkHttpClient
OkHttpClient customClient = new OkHttpClient.Builder()
        .addInterceptor(authInterceptor)
        // 这里还可以添加其他你需要的配置,比如超时时间、缓存等
        .build();

// 配置并初始化PRDownloader
PRDownloaderConfig downloaderConfig = PRDownloaderConfig.newBuilder()
        .setOkHttpClient(customClient)
        .build();

PRDownloader.initialize(getApplicationContext(), downloaderConfig);

3. 动态更新令牌(可选)

如果你的accessToken有过期时间,后续需要刷新的话,直接调用拦截器的updateAccessToken方法就行,不用重新初始化PRDownloader:

// 当获取到新的accessToken后,更新拦截器里的令牌
authInterceptor.updateAccessToken("新的Google Drive访问令牌");

注意事项

  • 这个方案依赖PRDownloader暴露的setOkHttpClient配置接口,虽然官方没专门提用来加认证头,但只要PRDownloader底层还是用OkHttp,这个方法就一直有效。
  • 确保你的Google Drive文件链接是可通过Bearer令牌访问的格式(比如使用Drive API的文件下载链接,而不是公开分享的普通链接)。

内容的提问来源于stack exchange,提问作者imin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:59:14