1

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

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

这是我的代码:

/**
 * 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());
4

1 回答 1

0

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

于 2012-12-05T21:11:12.277 回答