gpt4 book ai didi

android - 如何以编程方式在android中下载谷歌驱动器选择的文件?

转载 作者:行者123 更新时间:2023-11-30 01:35:32 25 4
gpt4 key购买 nike

谷歌驱动器选择代码如下:

private void initializeGoogleDrive() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();

}

@Override
public void onConnected(Bundle bundle) {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"text/plain", "text/html"})
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Utility.appLog(TAG, "Unable to send intent");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_OPENER) {
if (resultCode == RESULT_OK) {
DriveId driveId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
String resourceId = driveId.getResourceId();
String downloadUrl = "https://drive.google.com/open?id=" + resourceId + "&export=download";
Utility.appLog(TAG, "Download Url :: " + downloadUrl);
}
}
}

我们可以获取下载 url,但不幸的是,由于我在尝试下载文件时出现身份验证错误,因此无法完成下载。

提前致谢。

最佳答案

在异步任务中执行此操作

try{
URL url = new URL(URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "OAuth " + GoogleAuthUtil.getToken(mContext, mCredential.getSelectedAccountName(), Constants.SCOPE));
conn.setDoInput(true);
// Starts the query
conn.connect();
int responseCode = conn.getResponseCode();
//you will recive the file in input stream
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");

FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = conn.getInputStream();

byte[] buffer = new byte[1024];
int bufferLength = 0;

while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
}

我正在使用依赖项,

compile 'com.google.android.gms:play-services-identity:8.3.0'
compile('com.google.api-client:google-api-client-android:1.20.0') {
exclude group: 'org.apache.httpcomponents'
}

关于android - 如何以编程方式在android中下载谷歌驱动器选择的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35153451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com