繁体   English   中英

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

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

我将跟踪developers.google.com中有关Drive v2的所有信息,以便在Android API 15中构建一个简单的应用程序,仅用于上传txt文件。 在花费了许多时间之后,像为库编写正确的Java构建路径(在我的情况下为1.11.0),启用和设置Drive SDK,对客户端ID的API访问等,花了很多时间。我在本文中找到了一个不错的示例Google云端硬盘将错误400或403返回我的Android应用程序? 在这里,我找到了与我上应用程序相同的错误描述。 这是我的完整代码(希望对其他人有用):

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.
    }
}

同时体现:

<?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>

但是总会出现以下错误:

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

在我看来,DRIVE SDK和Drive API没有错误。 有什么建议吗? 请!!

您将从API控制台获得的客户端ID传递给driveRequest.setKey,但是该方法用于设置API密钥而不是客户端ID。 有关更多详细信息,请检查您提到的另一个问题的第一个答案。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM