java - 我如何用java编写批处理程序来上传Google Drive中的文件?

标签 java google-docs google-docs-api google-drive-api

我已经编写了一些在 Google Drive 中成功上传图像的代码,但我需要在浏览器中复制运行该项目并在浏览器中获取代码后获得的授权代码。我需要在控制台中复制此代码,然后它就可以正常工作。

但我正在尝试制作用于上传图像的批处理文件,因此不需要这些手动工作。 请帮我。 提前致谢。

这是我的代码:

/**
 * Client id from GD.
 */
private static String CLIENT_ID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
/**
 * Client secret key from GD.
 */
private static String CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

/**
 * Redirect url from GD.
 */
private static String REDIRECT_URI = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

  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("online")
        .setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    System.out.println("Please open the following URL in your browser then type the authorization code:");
    System.out.println("  " + url);
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String code = br.readLine();

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    //Create a new authorized API client
    Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

    //Insert a file  
    File body = new File();
    body.setTitle("imagename");
    body.setDescription("A test document");
    body.setMimeType("image/jpeg");

    java.io.File fileContent = new java.io.File("icon.jpg");
    FileContent mediaContent = new FileContent("image/jpeg", fileContent);

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

最佳答案

您只需在首次运行应用程序时完成授权流程。然后,您可以存储刷新 token 并使用它来构建授权请求所需的凭证对象。刷新 token 将持续到用户手动撤销为止。

关于java - 我如何用java编写批处理程序来上传Google Drive中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718100/

相关文章:

google-docs - 通过 Google Apps 脚本将图像添加到 Google 文档

file-format - Google Docs 如何存储文档(在后端)?

google-docs - 如何使用 Google Docs API 编辑 Google Docs 标题?

java - 记住桌面应用程序中 Google Drive API 的最后一个 oAuth2 session

java - 父类的私有(private)成员用作公共(public)成员函数的参数

java - SSLContext 模拟未按预期运行

html - 格式化 HTML 表格以粘贴到 Google 文档中

java - 使用 Java 查找基元数组中的最大值/最小值

java - Flink 流式传输 - 使用 StreamingFileSink 时更改部分文件名?

google-drive-api - 如何获取谷歌文档图片的网址