我正在尝试使用Google服务帐户将文件上传到Google云端硬盘。
驱动程序服务
public static Drive getDriveService(String secretKeyFile) throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(DriveScopes.DRIVE)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(secretKeyFile))
.build();
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).setApplicationName("appl name").build();
return service;
}
插入文件
private static File insertFile(Drive service, String title, String description,String mimeType, String filename) {
File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);
try {
File file = service.files().insert(body, mediaContent).execute();
return file;
} catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
主要方法
Drive service=null;
try {
String secretFile= "somedigit-privatekey.p12";
service = getDriveService(secretFile);
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
File insertFile = insertFile(service, "test title", "File description", "text/plain", "c:\\test.txt");
List list = service.files().list();
System.out.println("Files Id : "+insertFile.getId());
System.out.println("Count Files : "+list.size());
现在,我的问题是:
答案 0 :(得分:3)
您正在创建列表请求但不执行它。使用execute
方法发出请求:
service.files().list().execute();
如果您将下载链接粘贴到浏览器中,它将以401响应,因为您的下载请求还应包含有效的授权标头。使用以下代码段以编程方式下载文件。
HttpResponse resp = service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
InputStream stream = resp.getContent();
stream
是文件内容的输入流。
或者在您在其他地方发出的请求中添加Authorization: Bearer <access token>
。