【问题标题】:How to Avoid redeeming Google Authorization Code every time如何避免每次都兑换 Google 授权码
【发布时间】:2016-01-09 08:04:51
【问题描述】:
    public class image {
    private String applicationName;

    public image setApplicationName(String applicationName) {
          this.applicationName = applicationName;
          return this;
        }
      private static String CLIENT_ID = "***";
      private static String CLIENT_SECRET = "***";
      private static String REDIRECT_URI = "https://developers.google.com/oauthplayground";

    public static void main(String[] args) throws IOException{
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
            .setAccessType("offline")
            .setApprovalPrompt("auto").build();


        String code = "4/-4JsvGiqNpZ6Ms5dLjLA2QgzgToGAxx_SZTeByBPh_Q";

        GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
        .build()
        .setFromTokenResponse(response);

        Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
        .setHttpRequestInitializer(credential)
        .setApplicationName("musik")
        .build();

        //Insert a file  
        File body = new File();
        body.setTitle("My document");
        body.setDescription("A test document");
        body.setMimeType("text/plain");

        java.io.File fileContent = new java.io.File("document.txt");
        FileContent mediaContent = new FileContent("text/plain", fileContent);

        File file = service.files().insert(body, mediaContent).execute();
        System.out.println("File ID: " + file.getId());
    }

}

我正在尝试使用 Drive Api 将文件上传到我的驱动器上,一切正常,但每次使用后我都必须兑换 Google 授权码。 是否有任何调整或方法可以使上述代码不使用任何刷新令牌或访问令牌方法每次都兑换我?

【问题讨论】:

    标签: google-drive-api authorization token


    【解决方案1】:

    您无需每次都兑换授权码。您获得授权码,然后在通过身份验证后刷新并访问令牌。因此,您可以使用刷新令牌来刷新访问令牌,然后进行谷歌驱动操作。

    内容正文应采用这种格式“client_id=[clientId]&client_secret=[clientSecret]&refresh_token=[RefreshToken]&grant_type=refresh_token”并执行 HTTP post 方法来刷新访问令牌。

    【讨论】:

    • Suhas 你能调整上面的代码来说明这个概念吗?
    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2020-08-25
    • 2021-05-19
    • 2014-10-31
    • 2021-12-16
    相关资源
    最近更新 更多