使用Google Api获取文档列表并下载它们? [英] Using Google Api fetch Documents list and download them?

查看:88
本文介绍了使用Google Api获取文档列表并下载它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我正在使用Picasa的例子为Android和修改它,但我没有得到任何文件列表Plz帮助我发布我修改的类休息是一样的,在Picasa的例子吗?Plz的帮助



在executeRefreshAlbums()方法中获得 400错误的请求。

FetchGooleDocsActivity(这是主要活动)

  package com.fetchgoogledocs; 

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

导入android.accounts.Account;
导入android.accounts.AccountManager;
导入android.app.AlertDialog;
导入android.app.Dialog;
导入android.app.ListActivity;
导入android.content.ContentResolver;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.SharedPreferences;
导入android.database.Cursor;
导入android.net.Uri;
导入android.os.Bundle;
导入android.provider.MediaStore.Images;
导入android.util.Log;
导入android.widget.ArrayAdapter;
导入android.widget.Toast;

导入com.google.api.client.googleapis.GoogleHeaders;
导入com.google.api.client.googleapis.GoogleTransport;
导入com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.xml.atom.AtomParser;

public class FetchGooleDocsActivity extends ListActivity {

private static final String AUTH_TOKEN_TYPE =writely;

private static final String TAG =PrinterAppGDOCS;


private static final int REQUEST_AUTHENTICATE = 0;

private static final String PREF =MyPrefs;

private static final int DIALOG_ACCOUNTS = 0;

私有静态HttpTransport传输;

private String authToken;
private static Context context;

私人字符串postLink;
private final List< AlbumEntry> albums = new ArrayList< AlbumEntry>();
//私人最终列表< AlbumEntry> albums = new ArrayList< AlbumEntry>();

public FetchGooleDocsActivity(){
transport = GoogleTransport.create();
GoogleHeaders headers =(GoogleHeaders)transport.defaultHeaders;
headers.setApplicationName(PrinterApp / 1.0);
headers.gdataVersion =2;
AtomParser解析器=新的AtomParser();
parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
transport.addParser(parser);
}

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
context = this;
SharedPreferences设置= getSharedPreferences(PREF,0);
setLogging(settings.getBoolean(logging,false));
getListView()。setTextFilterEnabled(true);
registerForContextMenu(getListView());
Intent intent = getIntent();
if(Intent.ACTION_SEND.equals(intent.getAction())){
sendData = new SendData(intent,getContentResolver());
Toast.makeText(上下文,发送数据初始化,Toast.LENGTH_SHORT).show();
} else if(Intent.ACTION_MAIN.equals(getIntent()。getAction())){
sendData = null;
}
gotAccount(false);

$ b $覆盖
保护对话框onCreateDialog(int id){
switch(id){
case DIALOG_ACCOUNTS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(选择Google帐户);
最终AccountManager经理= AccountManager.get(this);
final Account [] accounts = manager.getAccountsByType(com.google);
final int size = accounts.length;
String [] names = new String [size];
for(int i = 0; i< size; i ++){
names [i] = accounts [i] .name;
}
builder.setItems(names,new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
gotAccount(manager,accounts [which]) ;
}
});
return builder.create();
}
返回null;
}

private void gotAccount(boolean tokenExpired){
SharedPreferences设置= getSharedPreferences(PREF,0);
String accountName = settings.getString(accountName,null);
if(accountName!= null){
AccountManager manager = AccountManager.get(this);
帐户[] accounts = manager.getAccountsByType(com.google);
int size = accounts.length;
for(int i = 0; i< size; i ++){
Account account = accounts [i];
if(accountName.equals(account.name)){
if(tokenExpired){
manager.invalidateAuthToken(com.google,this.authToken);
}
gotAccount(manager,account);
return;
}
}
}
showDialog(DIALOG_ACCOUNTS);
}

private void gotAccount(最终AccountManager经理,最终账户账户){
SharedPreferences设置= getSharedPreferences(PREF,0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(accountName,account.name);
editor.commit();
new Thread(){

@Override
public void run(){
try {
final Bundle bundle =
manager.getAuthToken (account,AUTH_TOKEN_TYPE,true,null,null)
.getResult();
runOnUiThread(new Runnable(){

public void run(){
try {
if(bundle.containsKey(AccountManager.KEY_INTENT)){
Intent intent =
bundle.getParcelable(AccountManager.KEY_INTENT);
int flags = intent.getFlags();
flags& =〜Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags (flags);
startActivityForResult(intent,REQUEST_AUTHENTICATE);
} else if(bundle.containsKey(AccountManager.KEY_AUTHTOKEN)){
authenticatedClientLogin(
bundle.getString(AccountManager.KEY_AUTHTOKEN ));
}
} catch(Exception e){
handleException(e);
}
}
});
} catch(Exception e){
handleException(e);
}
}
} .start();

$ b @Override
protected void onActivityResult(
int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data );
switch(requestCode){
case REQUEST_AUTHENTICATE:
if(resultCode == RESULT_OK){
gotAccount(false);
} else {
showDialog(DIALOG_ACCOUNTS);
}
break;
}
}

private void authenticatedClientLogin(String authToken){
this.authToken = authToken;
((GoogleHeaders)transport.defaultHeaders).setGoogleLogin(authToken);
authenticated();
}

static class SendData {

String fileName;
Uri uri;
字符串contentType;
long contentLength;

SendData(Intent intent,ContentResolver contentResolver){
Toast.makeText(context,Send data,Toast.LENGTH_SHORT).show();
Bundle extras = intent.getExtras();
if(extras.containsKey(Intent.EXTRA_STREAM)){
Uri uri = this.uri =(Uri)extras.getParcelable(Intent.EXTRA_STREAM);
String scheme = uri.getScheme();
Toast.makeText(context,scheme,Toast.LENGTH_LONG).show();
if(scheme.equals(content)){
Cursor cursor = contentResolver.query(uri,null,null,null,null);
cursor.moveToFirst();
this.fileName = cursor.getString(
cursor.getColumnIndexOrThrow(Images.Media.DISPLAY_NAME));
this.contentType = intent.getType();
this.contentLength =
cursor.getLong(cursor.getColumnIndexOrThrow(Images.Media.SIZE));
}
}
}
}

static SendData sendData;
$ b $ private void authenticated(){
if(sendData!= null){
try {
if(sendData.fileName!= null){
布尔成功= false;
尝试{
HttpRequest request = transport.buildPostRequest();
request.url = GdocUrl.relativeToRoot(
default / private / full);
Toast.makeText(context,request.url.toString(),Toast.LENGTH_LONG).show();
((GoogleHeaders)request.headers).setSlugFromFileName(
sendData.fileName);
InputStreamContent content = new InputStreamContent();
content.inputStream =
getContentResolver()。openInputStream(sendData.uri);
content.type = sendData.contentType;
content.length = sendData.contentLength;
request.content = content;
request.execute()。ignore();
success = true;
} catch(IOException e){
handleException(e);
}
setListAdapter(new ArrayAdapter< String>(this,
android.R.layout.simple_list_item_1,
new String [] {success?OK:ERROR} ));
}
} finally {
sendData = null;
}
} else {
executeRefreshAlbums();



private void executeRefreshAlbums(){
String [] albumNames;
列表< AlbumEntry> albums = this.albums;
albums.clear();
尝试{
GdocUrl url = GdocUrl.relativeToRoot(default / private / full);
//通过结果页面
while(true){
UserFeed userFeed = UserFeed.executeGet(transport,url);
this.postLink = userFeed.getPostLink();
if(userFeed.albums!= null){
albums.addAll(userFeed.albums);
}
字符串nextLink = userFeed.getNextLink();
if(nextLink == null){
break;
}
}
int numAlbums = albums.size();
albumNames = new String [numAlbums];
for(int i = 0; i< numAlbums; i ++){
albumNames [i] = albums.get(i).title;
}
} catch(IOException e){
Toast.makeText(context,e.getMessage(),Toast.LENGTH_LONG).show();
handleException(e);
albumNames = new String [] {e.getMessage()};
albums.clear();
}
setListAdapter(new ArrayAdapter< String>(
this,android.R.layout.simple_list_item_1,albumNames));
Toast.makeText(context,albumNames.toString(),Toast.LENGTH_LONG).show();


private void setLogging(boolean logging){
Logger.getLogger(com.google.api.client).setLevel(
logging?Level。 CONFIG:Level.OFF);
SharedPreferences设置= getSharedPreferences(PREF,0);
boolean currentSetting = settings.getBoolean(logging,false);
if(currentSetting!= logging){
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(logging,logging);
editor.commit();



private void handleException(Exception e){
e.printStackTrace();
SharedPreferences设置= getSharedPreferences(PREF,0);
boolean log = settings.getBoolean(logging,false);
if(e instanceof HttpResponseException){
HttpResponse response =((HttpResponseException)e).response;
int statusCode = response.statusCode;
尝试{
response.ignore();
} catch(IOException e1){
e1.printStackTrace();
}
if(statusCode == 401 || statusCode == 403){
gotAccount(true);
return;

if(log){
try {
Log.e(TAG,response.parseAsString());
} catch(IOException parseException){
parseException.printStackTrace(); $($)


$ b if(log){
Log.e(TAG,e.getMessage(),e);
}
}
}

GdocUrl

  package com.fetchgoogledocs; 

导入com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
$ b $ **
* @author Yaniv Inbar
* /
public class GdocUrl extends GoogleUrl {

public static final String ROOT_URL = https://docs.google.com/feeds/;

@Key
public String种类;

public GdocUrl(String encodedUrl){
super(encodedUrl);
}

/ **
*根据给定的相对路径构造一个新的URL。
*
* @param relativePath编码路径相对于{@link #ROOT_URL}
* @return新URL
* /
public static GdocUrl relativeToRoot(String relativePath ){
返回新的GdocUrl(ROOT_URL + relativePath);


code

$ b $ Mainfest

 <?xml version =1.0encoding =utf-8?> 
< manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.google.api.client.sample.picasa
android:versionCode =1
android:versionName =1.0>
< uses-sdk android:minSdkVersion =7/>

<使用权限android:name =android.permission.INTERNET/>
<使用权限android:name =android.permission.GET_ACCOUNTS/>
< uses-permission android:name =android.permission.USE_CREDENTIALS/>
<使用权限android:name =android.permission.MANAGE_ACCOUNTS/>
< application android:icon =@ drawable / iconandroid:label =@ string / app_name
android:debuggable =true>
< activity android:name =。PicasaDemoActivityandroid:label =@ string / app_name>
< intent-filter>
< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter>
< intent-filter>
< action android:name =android.intent.action.SEND>< / action>
< category android:name =android.intent.category.DEFAULT>< / category>
< data android:mimeType =image / *>< / data>
< / intent-filter>
< / activity>
< / application>
< / manifest>

UserFeed

  import com.google.api.client.http.HttpTransport; 
import com.google.api.client.util.Key;

import java.io.IOException;
import java.util.List;

public class UserFeed扩展Feed {

@Key(entry)
public List< AlbumEntry>专辑;

public static UserFeed executeGet(HttpTransport transport,GdocUrl url)
抛出IOException {
url.kinds =album;
return(UserFeed)Feed.executeGet(transport,url,UserFeed.class);


$ / code $ / pre



$ b

  import com.google.api.client.googleapis.xml.atom.GData; 
导入com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;

import java.io.IOException;
import java.util.List;
$ b $ **
* @author Yaniv Inbar
* /
公共类Feed {

@Key(link)
公开列表< Link>链接;

public String getPostLink(){
return Link.find(links,http://schemas.google.com/g/2005#post);
}

public String getNextLink(){
return Link.find(links,next);
}

static Feed executeGet(HttpTransport transport,GdocUrl url,$ b $ Class Class< ;? extends Feed> feedClass)throws IOException {
url.fields = GData.getFieldsFor( feedClass);
HttpRequest request = transport.buildGetRequest();
request.url = url;
返回request.execute()。parseAs(feedClass);


$ / code>

我认为我的问题在于 Feed Userfeed class导致我不知道要在URL中放什么

解决方案

您需要设置版本。从称为指定版本的API文档部分。 。


如果您向仅使用
版本3中的功能的API发出请求,但忘记设置版本,您很可能会收到
a 400的错误请求响应。由于版本2和3之间的URL结构不同
,这是API的新用户
所犯的常见错误。



指定一个版本号,使用GData-Version HTTP头。这个头部的
值必须是3.0。




  GData-Version:3.0 




或者,您可以在URL中指定v = 3作为查询参数。
在防火墙后面工作时,通常需要这样做,该防火墙会剥离HTTP
标头或某些JavaScript请求。如果可能,建议使用HTTP标头




  https:// docs.google.com/feeds/default/private/full?v=3 


Hi i am using the picasa example for android and modifying it but i am not getting any list of documents Plz help i am posting my modified class rest are same as in picasa example?Plz help

m getting 400 bad request in executeRefreshAlbums() method

FetchGooleDocsActivity(This is the main Activity)

package com.fetchgoogledocs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.xml.atom.AtomParser;

public class FetchGooleDocsActivity extends ListActivity {

     private static final String AUTH_TOKEN_TYPE = "writely";

      private static final String TAG = "PrinterAppGDOCS";


      private static final int REQUEST_AUTHENTICATE = 0;

      private static final String PREF = "MyPrefs";

      private static final int DIALOG_ACCOUNTS = 0;

      private static HttpTransport transport;

      private String authToken;
      private static Context context;

      private String postLink;
      private final List<AlbumEntry> albums = new ArrayList<AlbumEntry>();
      //private final List<AlbumEntry> albums = new ArrayList<AlbumEntry>();

      public FetchGooleDocsActivity() {
        transport = GoogleTransport.create();
        GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
        headers.setApplicationName("PrinterApp/1.0");
        headers.gdataVersion = "2";
        AtomParser parser = new AtomParser();
        parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
        transport.addParser(parser);
      }

      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context=this;
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        setLogging(settings.getBoolean("logging", false));
        getListView().setTextFilterEnabled(true);
        registerForContextMenu(getListView());
        Intent intent = getIntent();
        if (Intent.ACTION_SEND.equals(intent.getAction())) {
          sendData = new SendData(intent, getContentResolver());
          Toast.makeText(context, "Send data initilize", Toast.LENGTH_SHORT).show();
        } else if (Intent.ACTION_MAIN.equals(getIntent().getAction())) {            
          sendData = null;
        }
        gotAccount(false);
      }

      @Override
      protected Dialog onCreateDialog(int id) {
        switch (id) {
          case DIALOG_ACCOUNTS:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Select a Google account");
            final AccountManager manager = AccountManager.get(this);
            final Account[] accounts = manager.getAccountsByType("com.google");
            final int size = accounts.length;
            String[] names = new String[size];
            for (int i = 0; i < size; i++) {
              names[i] = accounts[i].name;
            }
            builder.setItems(names, new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                gotAccount(manager, accounts[which]);
              }
            });
            return builder.create();
        }
        return null;
      }

      private void gotAccount(boolean tokenExpired) {
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        String accountName = settings.getString("accountName", null);
        if (accountName != null) {
          AccountManager manager = AccountManager.get(this);
          Account[] accounts = manager.getAccountsByType("com.google");
          int size = accounts.length;
          for (int i = 0; i < size; i++) {
            Account account = accounts[i];
            if (accountName.equals(account.name)) {
              if (tokenExpired) {
                manager.invalidateAuthToken("com.google", this.authToken);
              }
              gotAccount(manager, account);
              return;
            }
          }
        }
        showDialog(DIALOG_ACCOUNTS);
      }

      private void gotAccount(final AccountManager manager, final Account account) {
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("accountName", account.name);
        editor.commit();
        new Thread() {

          @Override
          public void run() {
            try {
              final Bundle bundle =
                  manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null)
                      .getResult();
              runOnUiThread(new Runnable() {

                public void run() {
                  try {
                    if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                      Intent intent =
                          bundle.getParcelable(AccountManager.KEY_INTENT);
                      int flags = intent.getFlags();
                      flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                      intent.setFlags(flags);
                      startActivityForResult(intent, REQUEST_AUTHENTICATE);
                    } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                      authenticatedClientLogin(
                          bundle.getString(AccountManager.KEY_AUTHTOKEN));
                    }
                  } catch (Exception e) {
                    handleException(e);
                  }
                }
              });
            } catch (Exception e) {
              handleException(e);
            }
          }
        }.start();
      }

      @Override
      protected void onActivityResult(
          int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
          case REQUEST_AUTHENTICATE:
            if (resultCode == RESULT_OK) {
              gotAccount(false);
            } else {
              showDialog(DIALOG_ACCOUNTS);
            }
            break;
        }
      }

      private void authenticatedClientLogin(String authToken) {
        this.authToken = authToken;
        ((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken);
        authenticated();
      }

      static class SendData {         

        String fileName;
        Uri uri;
        String contentType;
        long contentLength;

        SendData(Intent intent, ContentResolver contentResolver) {
              Toast.makeText(context, "Send data", Toast.LENGTH_SHORT).show();
          Bundle extras = intent.getExtras();
          if (extras.containsKey(Intent.EXTRA_STREAM)) {
            Uri uri = this.uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
            String scheme = uri.getScheme();
            Toast.makeText(context, scheme, Toast.LENGTH_LONG).show();
            if (scheme.equals("content")) {
              Cursor cursor = contentResolver.query(uri, null, null, null, null);
              cursor.moveToFirst();
              this.fileName = cursor.getString(
                  cursor.getColumnIndexOrThrow(Images.Media.DISPLAY_NAME));
              this.contentType = intent.getType();
              this.contentLength =
                  cursor.getLong(cursor.getColumnIndexOrThrow(Images.Media.SIZE));
            }
          }      
        }
      }

      static SendData sendData;

      private void authenticated() {
        if (sendData != null) {
          try {
            if (sendData.fileName != null) {
              boolean success = false;
              try {
                HttpRequest request = transport.buildPostRequest();
                request.url = GdocUrl.relativeToRoot(
                    "default/private/full");
                Toast.makeText(context, request.url.toString(), Toast.LENGTH_LONG).show();
                ((GoogleHeaders) request.headers).setSlugFromFileName(
                    sendData.fileName);
                InputStreamContent content = new InputStreamContent();
                content.inputStream =
                    getContentResolver().openInputStream(sendData.uri);
                content.type = sendData.contentType;
                content.length = sendData.contentLength;
                request.content = content;
                request.execute().ignore();
                success = true;
              } catch (IOException e) {
                handleException(e);
              }
              setListAdapter(new ArrayAdapter<String>(this,
                  android.R.layout.simple_list_item_1,
                  new String[] {success ? "OK" : "ERROR"}));
            }
          } finally {
            sendData = null;
          }
        } else {        
         executeRefreshAlbums();
        }
      }

      private void executeRefreshAlbums() {      
            String[] albumNames;
            List<AlbumEntry> albums = this.albums;
            albums.clear();
            try {
              GdocUrl url = GdocUrl.relativeToRoot("default/private/full");           
              // page through results
              while (true) {
                UserFeed userFeed = UserFeed.executeGet(transport, url);                
                this.postLink = userFeed.getPostLink();
                if (userFeed.albums != null) {
                  albums.addAll(userFeed.albums);
                }
                String nextLink = userFeed.getNextLink();
                if (nextLink == null) {
                  break;
                }
              }
              int numAlbums = albums.size();
              albumNames = new String[numAlbums];
              for (int i = 0; i < numAlbums; i++) {
                albumNames[i] = albums.get(i).title;
              }
            } catch (IOException e) {
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
              handleException(e);
              albumNames = new String[] {e.getMessage()};
              albums.clear();
            }
            setListAdapter(new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, albumNames));
            Toast.makeText(context, albumNames.toString(), Toast.LENGTH_LONG).show();
          }

      private void setLogging(boolean logging) {
        Logger.getLogger("com.google.api.client").setLevel(
            logging ? Level.CONFIG : Level.OFF);
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        boolean currentSetting = settings.getBoolean("logging", false);
        if (currentSetting != logging) {
          SharedPreferences.Editor editor = settings.edit();
          editor.putBoolean("logging", logging);
          editor.commit();
        }
      }

      private void handleException(Exception e) {
        e.printStackTrace();
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        boolean log = settings.getBoolean("logging", false);
        if (e instanceof HttpResponseException) {
          HttpResponse response = ((HttpResponseException) e).response;
          int statusCode = response.statusCode;
          try {
            response.ignore();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
          if (statusCode == 401 || statusCode == 403) {
            gotAccount(true);
            return;
          }
          if (log) {
            try {
              Log.e(TAG, response.parseAsString());
            } catch (IOException parseException) {
              parseException.printStackTrace();
            }
          }
        }
        if (log) {
          Log.e(TAG, e.getMessage(), e);
        }
      }
    }

GdocUrl

package com.fetchgoogledocs;

import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;

/**
 * @author Yaniv Inbar
 */
public class GdocUrl extends GoogleUrl {

  public static final String ROOT_URL = "https://docs.google.com/feeds/";

  @Key
  public String kinds;

  public GdocUrl(String encodedUrl) {
    super(encodedUrl);
  }

  /**
   * Constructs a new URL based on the given relative path.
   * 
   * @param relativePath encoded path relative to the {@link #ROOT_URL}
   * @return new URL
   */
  public static GdocUrl relativeToRoot(String relativePath) {
    return new GdocUrl(ROOT_URL + relativePath);
  }
}

Mainfest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.google.api.client.sample.picasa"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />

 <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
  <uses-permission android:name="android.permission.USE_CREDENTIALS" />
  <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
  <application android:icon="@drawable/icon" android:label="@string/app_name"
    android:debuggable="true">
    <activity android:name=".PicasaDemoActivity" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.SEND"></action>
        <category android:name="android.intent.category.DEFAULT"></category>
        <data android:mimeType="image/*"></data>
      </intent-filter>
    </activity>    
    </application>
</manifest>

UserFeed

import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;

import java.io.IOException;
import java.util.List;

public class UserFeed extends Feed {

  @Key("entry")
  public List<AlbumEntry> albums;

  public static UserFeed executeGet(HttpTransport transport, GdocUrl url)
      throws IOException {
    url.kinds = "album";
    return (UserFeed) Feed.executeGet(transport, url, UserFeed.class);
  }
}

Feed

import com.google.api.client.googleapis.xml.atom.GData;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;

import java.io.IOException;
import java.util.List;

/**
 * @author Yaniv Inbar
 */
public class Feed {

  @Key("link")
  public List<Link> links;

  public String getPostLink() {
    return Link.find(links, "http://schemas.google.com/g/2005#post");
  }

  public String getNextLink() {
    return Link.find(links, "next");
  }

  static Feed executeGet(HttpTransport transport, GdocUrl url,
      Class<? extends Feed> feedClass) throws IOException {
    url.fields = GData.getFieldsFor(feedClass);
    HttpRequest request = transport.buildGetRequest();
    request.url = url;
    return request.execute().parseAs(feedClass);
  }
}

I think my problem lies in Feed or Userfeed class cause i dont know what to put next in URL

解决方案

You need to set the version. From the API documentation section called Specifying a Version ...

If you make a request to the API that uses a feature only available in version 3, but forget to set the version, you will most likely receive a 400 Bad Request response. Since the URL structure is different between versions 2 and 3, this is a common mistake made by new users of the API.

To specify a version number, use the GData-Version HTTP header. The value of this header must be 3.0. The decimal and the zero are required.

GData-Version: 3.0

Alternatively, you can specify v=3 as a query parameter in the URL. This is often needed when working behind a firewall that strips HTTP headers, or from some JavaScript requests. Use of the HTTP header is recommended when possible.

https://docs.google.com/feeds/default/private/full?v=3

这篇关于使用Google Api获取文档列表并下载它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆