我遵循了 google drive sdk 中提到的所有步骤。我在我的设备(android,运行果冻豆)上创建了一个示例应用程序,并且能够将文件上传到驱动器。尝试下载同一个文件时,我能够获取文件 ID、文件标题、文件下载 URL 等元数据,但无法下载内容。我收到 401 未经授权的错误。
我的应用 AUTH SCOPE 是 AUTH_TOKEN_TYPE = "oauth2: https://www.googleapis.com/auth/drive.file ";
我正在执行以下操作来获取 OAUTH 令牌:
AccountManager am = AccountManager.get(this);
Bundle options = new Bundle();
am.getAuthToken(
mAccount,
AUTH_TOKEN_TYPE,
options,
this,
new OnTokenAcquired(),
new Handler(){
@Override
public void handleMessage(Message msg) {
invadiateToken();
super.handleMessage(msg);
}
});
基于令牌,这就是我构建 Drive 对象的方式
Drive buildService(final String AuthToken) {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
@Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey(API_KEY);
driveRequest.setOauthToken(AuthToken);
}
});
return b.build();
}
我可以使用以下代码上传文件:
private void uploadLocalFileToDrive(Drive service) throws IOException{
// File's metadata.
String mimeType = "text/plain";
File body = new File();
body.setTitle("myText.txt");
body.setDescription("sample app by varun");
body.setMimeType("text/plain");
// File's content.
java.io.File fileContent = new java.io.File(mInternalFilePath);
FileContent mediaContent = new FileContent(mimeType, fileContent);
service.files().insert(body, mediaContent).execute();
}
在尝试下载此应用上传的相同文件时,我HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute()
在以下代码段的此行收到 401 未经授权的错误
private void downloadFileFromDrive(Drive service) throws IOException {
Files.List request;
request = service.files().list();
do {
FileList files = request.execute();
for(File file:files.getItems()){
String fieldId = file.getId();
String title = file.getTitle();
Log.e("MS", "MSV:: Title-->"+title+" FieldID-->"+fieldId+" DownloadURL-->"+file.getDownloadUrl());
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0 ) {
GenericUrl url = new GenericUrl(file.getDownloadUrl());
HttpResponse resp = service.getRequestFactory().buildGetRequest(url).execute();
InputStream isd = resp.getContent();
Log.e("MS", "MSV:: FileOutPutStream--->"+getFilesDir().getAbsolutePath()+"/downloaded.txt");
} else {
Log.e("MS", "MSV:: downloadURL for this file is null");
}
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken()!=null && request.getPageToken().length()>0);
}
谁能帮助我,让我知道我做错了什么???