我想使用我存储的凭证文件,请帮帮我。桌面APP。我不明白如何使用保存的凭证。我没有在谷歌支持上找到一些说明。
private static final String APPLICATION_NAME
= "edocsAPI";
private static final java.io.File DATA_STORE_DIR = new java.io.File(
"E:/", ".credentials/drive-java-quickstart");
private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final JsonFactory JSON_FACTORY
= JacksonFactory.getDefaultInstance();
private static HttpTransport HTTP_TRANSPORT;
private static final List<String> SCOPES
= Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in
= new FileInputStream("E:/client_secret_Rep.json");
GoogleClientSecrets clientSecrets
= GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow
= new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential
= new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
return credential;
}
public static Drive getDriveService() throws IOException {
Credential credential =
authorize();
System.out.println("getAccessToken" + credential.getAccessToken());
System.out.println("setAccessToken" + credential.getAccessToken());
System.out.println("setExpiresInSeconds" + credential.getExpiresInSeconds());
System.out.println("setRefreshToken" + credential.getRefreshToken());
return new Drive.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Drive service = getDriveService();
FileList result = service.files().list()
.setMaxResults(10)
.execute();
List<File> files = result.getItems();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getTitle(), file.getId() , file.getAlternateLink());
file.setShared(Boolean.TRUE);
System.out.println(file.getAlternateLink());
}
}
}
我尝试这样做:
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setClientSecrets("Client ID",
"ClientSecrets").build();
credential.setAccessToken("AccessToken");
但我有错误401
答案 0 :(得分:1)
看起来由于过期或无效的访问令牌而发生错误。
无效的授权标头。您正在使用的访问令牌已过期或无效。
以下是documentation对401错误的建议。
建议的操作:使用长期刷新令牌刷新访问令牌。如果此操作失败,请引导用户完成OAuth流程,如Authorizing Your App with Google Drive。
中所述