简体   繁体   English

我的Android应用中的Google云端硬盘返回错误400

[英]Google Drive Returning Error 400 in my Android app

I'm following all information about Drive v2 in developers.google.com in order to build a simple app in Android API 15 just to upload a txt file. 我将跟踪developers.google.com中有关Drive v2的所有信息,以便在Android API 15中构建一个简单的应用程序,仅用于上传txt文件。 After many hours spent in all around it like the right java build path for libraries (1.11.0 in my case), enable and set up Drive SDK, API access for client ID, etc, etc. I found a nice example in this post Google Drive Returning Error 400 or 403 to my Android App? 在花费了许多时间之后,像为库编写正确的Java构建路径(在我的情况下为1.11.0),启用和设置Drive SDK,对客户端ID的API访问等,花了很多时间。我在本文中找到了一个不错的示例Google云端硬盘将错误400或403返回我的Android应用程序? where I found the same error description that now I'm getting on my app. 在这里,我找到了与我上应用程序相同的错误描述。 This is my full code (hope useful to others): 这是我的完整代码(希望对其他人有用):

public class DrivexampleActivity extends Activity { 

Context activity = null;
boolean alreadyTriedAgain;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AccountManager am = AccountManager.get(this);
    activity = this.getApplicationContext();
    Bundle options = new Bundle();
    Account[] acc = am.getAccounts();
    am.getAuthToken(
        (am.getAccounts())[8], // #8 just in my phone case. you can debugg the acc variable to find your @gmail account index.
        "oauth2:" + DriveScopes.DRIVE,
        options,
        true, 
        new OnTokenAcquired(),
        null); 
}

private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    @Override
    public void run(AccountManagerFuture<Bundle> result) {

        try {
            final String token = result.getResult().getString(AccountManager.KEY_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 {
            // TODO Auto-generated method stub
                DriveRequest driveRequest = (DriveRequest) request;
                driveRequest.setPrettyPrint(true);                              
                driveRequest.setKey("xxxxxxxxxxxx.apps.googleusercontent.com"); // I replaced the number with x's. for your Client ID from Google API Console
                driveRequest.setOauthToken(token);                      
                }
            }); 

                final Drive drive = b.build();

                final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
                body.setTitle("My Test File");
                body.setDescription("A Test File");
                body.setMimeType("text/plain");

                java.io.File fileContent = new java.io.File("document.txt");
                final FileContent mediaContent = new FileContent("text/plain",fileContent);

                new Thread(new Runnable() {
                    public void run() {

                        com.google.api.services.drive.model.File file;
                        try {                           
                            file = drive.files().insert(body, mediaContent).execute();
                            Log.i("Hi", "File ID: " + file.getId());
                            alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
                        } catch (IOException e) {
                            if(!alreadyTriedAgain){
                                alreadyTriedAgain = true;
                                Log.i("Hi", "The upload/insert was caught, which suggests it wasn't successful...");
                                e.printStackTrace();    
                            }    
                        }
                    }
                }).start();

                Intent launch = null;
                launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);

                if (launch != null) {
                    Log.i("Hi", "Something came back as a KEY_INTENT");
                    startActivityForResult(launch, 3025);
                    return; 
                }
        } catch (OperationCanceledException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (AuthenticatorException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }        
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 3025) {
        switch (resultCode) {
            case RESULT_OK:
                AccountManager am = AccountManager.get(activity);
                Bundle options = new Bundle();
                am.getAuthToken(
                        (am.getAccounts())[8], // #8 just in my phone case. you can debugg the acc variable to find your @gmail account index.
                        "oauth2:" + DriveScopes.DRIVE,
                        options,
                        true, 
                        new OnTokenAcquired(),
                        null); 
                break;
            case RESULT_CANCELED:
                // This probably means the user refused to log in. Explain to them why they need to log in.
                break;
            default:
                // This isn't expected... maybe just log whatever code was returned.
                break;
        }
    } else {
        // Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like.
    }
}

Also manifest: 同时体现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.drivexample"
android:versionCode="1"
android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DrivexampleActivity"
            android:label="@string/app_name" 
            android:exported="true">
            <meta-data android:name="com.google.android.apps.drive.APP_ID" android:value="id=xxxxxxxxxxxx"/>

            <intent-filter>
                <action android:name="com.google.android.apps.drive.DRIVE_OPEN" />
                <data android:mimeType="application/vnd.test.type"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

But allways get the following error: 但是总会出现以下错误:

com.google.api.client.http.HttpResponseException: 400 Bad Request
{
  "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "keyInvalid",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }
}

Seems that no errors with DRIVE SDK and Drive API in my case. 在我看来,DRIVE SDK和Drive API没有错误。 Any suggestion?? 有什么建议吗? please!! 请!!

You are passing the Client ID you got from the APIs Console to driveRequest.setKey, however that method is used to set an API Key and not the Client ID. 您将从API控制台获得的客户端ID传递给driveRequest.setKey,但是该方法用于设置API密钥而不是客户端ID。 Check the first answer to the other question you mentioned for more details. 有关更多详细信息,请检查您提到的另一个问题的第一个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在我的Android应用中管理Google云端硬盘上的文件 - Managing files on Google Drive in my Android app Android:如何使我的应用记住Google云端硬盘授权? - Android: how to make my app remember Google Drive Authorization? 如何在我的 Android 应用中显示上传到 Google Drive 的进度? - How to show uploading to Google Drive progress in my android App? Jsoup在Google Maps API上返回错误400 - Jsoup returning an error 400 on Google Maps API 无法从我的Android应用com.google.android.gms.auth.GoogleAuthException上传到Google驱动器:未知 - cannot upload to google drive from my android app com.google.android.gms.auth.GoogleAuthException: Unknown 如何仅使用Google Android应用中的Google Drive API在Google云端硬盘上创建和编辑电子表格文件? - How do I create & edit a spreadsheet file on google drive using Google Drive APIs only from my Android app? 使用Google Drive API备份我的应用 - Using Google Drive API to backup my app 使用谷歌驱动器存储Android应用程序数据 - Use google drive to store android app data Android Google Drive SDK:保存到应用程序文件夹 - Android Google Drive SDK: Saving to App Folder 如何将图像从我的Android应用程序上传到Google驱动器上的特定文件夹 - how to upload an image from my android app to a specific folder on google drive
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM