我已经编写了一些代码,可以在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());
答案 0 :(得分:0)
首次运行应用时,您只需要完成授权流程。然后,您可以存储刷新令牌并使用它来构建授权请求所需的凭据对象。刷新令牌持续到用户手动撤销为止。