使用Goople阿比获取文件列表,并下载他们呢? [英] Using Goople Api fetch Documents list and download them?

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

问题描述

你好我使用Android版Picasa的例子,修改它,但我没有得到的文件plz帮助任何列表我张贴我修改的类其余均相同Picasa中的例子吗?plz帮助

m到处在executeRefreshAlbums 400错误的请求()方法

FetchGooleDocsActivity(这是主要的活动)

 包com.fetchgoogledocs;

进口java.io.IOException异常;
进口的java.util.ArrayList;
进口的java.util.List;
进口java.util.logging.Level中;
进口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.Shared preferences;
进口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.Htt prequest;
进口com.google.api.client.http.Htt presponse;
进口com.google.api.client.http.Htt presponseException;
进口com.google.api.client.http.HttpTransport;
进口com.google.api.client.http.InputStreamContent;
进口com.google.api.client.xml.atom.AtomParser;

公共类FetchGooleDocsActivity扩展ListActivity {

     私有静态最后弦乐AUTH_TOKEN_TYPE =Writely的;

      私有静态最后字符串变量=PrinterAppGDOCS;


      私有静态最终诠释REQUEST_AUTHENTICATE = 0;

      私有静态最后弦乐preF =我的preFS;

      私有静态最终诠释DIALOG_ACCOUNTS = 0;

      私有静态HttpTransport运输;

      私人字符串的authToken;
      私有静态上下文的背景下;

      私人字符串postLink;
      私人最终名单,其中,AlbumEntry>专辑=新的ArrayList< AlbumEntry>();
      //私人最终名单,其中,AlbumEntry>专辑=新的ArrayList< AlbumEntry>();

      公共FetchGooleDocsActivity(){
        运输= GoogleTransport.create();
        GoogleHeaders标题=(GoogleHeaders)transport.defaultHeaders;
        headers.setApplicationName(PrinterApp / 1.0);
        headers.gdataVersion =2;
        AtomParser分析器=新AtomParser();
        parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
        transport.addParser(分析器);
      }

      @覆盖
      公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        上下文=这一点;
        共享preferences设置= getShared preferences(preF,0);
        setLogging(settings.getBoolean(记录,FALSE));
        getListView()setTextFilterEnabled(真)。
        registerForContextMenu(getListView());
        意向意图= getIntent();
        如果(Intent.ACTION_SEND.equals(intent.getAction())){
          送出数据=新的SendData(意向,getContentResolver());
          Toast.makeText(背景下,发送的数据用来初始化,Toast.LENGTH_SHORT).show();
        }否则,如果(Intent.ACTION_MAIN.equals(getIntent()的getAction())){
          送出数据= ​​NULL;
        }
        gotAccount(假);
      }

      @覆盖
      受保护的对话框onCreateDialog(INT ID){
        开关(ID){
          案例DIALOG_ACCOUNTS:
            AlertDialog.Builder建设者=新AlertDialog.Builder(本);
            builder.setTitle(选择一个谷歌帐户);
            最后的AccountManager经理= AccountManager.get(本);
            决算[]帐户= manager.getAccountsByType(com.google);
            最终诠释大小= accounts.length;
            的String []的名称=新的String [尺寸]
            的for(int i = 0; I<大小;我++){
              名称[I] =帐户[我]。名称;
            }
            builder.setItems(名称,新DialogInterface.OnClickListener(){
              公共无效的onClick(DialogInterface对话,诠释它){
                gotAccount(经理,应收[它]);
              }
            });
            返回builder.create();
        }
        返回null;
      }

      私人无效gotAccount(布尔tokenExpired){
        共享preferences设置= getShared preferences(preF,0);
        字符串帐户名= settings.getString(帐户名,NULL);
        如果(帐户名!= NULL){
          的AccountManager经理= AccountManager.get(本);
          帐户[]帐户= manager.getAccountsByType(com.google);
          INT大小= accounts.length;
          的for(int i = 0; I<大小;我++){
            账户账户=账户[I]
            如果(accountName.equals(account.name)){
              如果(tokenExpired){
                manager.invalidateAuthToken(com.google,this.authToken);
              }
              gotAccount(经理,帐户);
              返回;
            }
          }
        }
        的ShowDialog(DIALOG_ACCOUNTS);
      }

      私人无效gotAccount(最终的AccountManager经理,决算账户){
        共享preferences设置= getShared preferences(preF,0);
        共享preferences.Editor编辑器= settings.edit();
        editor.putString(帐户名,account.name);
        editor.commit();
        新的Thread(){

          @覆盖
          公共无效的run(){
            尝试 {
              最后的捆绑包=
                  manager.getAuthToken(帐户,AUTH_TOKEN_TYPE,真实,NULL,NULL)
                      .getResult();
              runOnUiThread(新的Runnable(){

                公共无效的run(){
                  尝试 {
                    如果(bundle.containsKey(AccountManager.KEY_INTENT)){
                      意向意图=
                          bundle.getParcelable(AccountManager.KEY_INTENT);
                      int的标志= intent.getFlags();
                      标志和放大器; =〜Intent.FLAG_ACTIVITY_NEW_TASK;
                      intent.setFlags(标志);
                      startActivityForResult(意向,REQUEST_AUTHENTICATE);
                    }否则,如果(bundle.containsKey(AccountManager.KEY_AUTHTOKEN)){
                      authenticatedClientLogin(
                          bundle.getString(AccountManager.KEY_AUTHTOKEN));
                    }
                  }赶上(例外五){
                    handleException(E);
                  }
                }
              });
            }赶上(例外五){
              handleException(E);
            }
          }
        }。开始();
      }

      @覆盖
      保护无效onActivityResult(
          INT请求code,INT结果code,意图数据){
        super.onActivityResult(要求code,因此code,数据);
        开关(要求code){
          案例REQUEST_AUTHENTICATE:
            如果(结果code == RESULT_OK){
              gotAccount(假);
            } 其他 {
              的ShowDialog(DIALOG_ACCOUNTS);
            }
            打破;
        }
      }

      私人无效authenticatedClientLogin(字符串的authToken){
        this.authToken =的authToken;
        ((GoogleHeaders)transport.defaultHeaders).setGoogleLogin(的authToken);
        认证();
      }

      静态类送出数据{

        字符串文件名;
        乌里URI;
        字符串的contentType;
        长CONTENTLENGTH;

        送出数据(意向意图,ContentResolver的ContentResolver的){
              Toast.makeText(背景下,发送数据,Toast.LENGTH_SHORT).show();
          捆绑额外= intent.getExtras();
          如果(extras.containsKey(Intent.EXTRA_STREAM)){
            开放的我们的uri = this.uri =(URI)extras.getParcelable(Intent.EXTRA_STREAM);
            字符串模式= uri.getScheme();
            Toast.makeText(背景下,方案,Toast.LENGTH_LONG).show();
            如果(scheme.equals(内容)){
              光标光标= 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));
            }
          }
        }
      }

      静态送出数据送出数据;

      私人无效认证(){
        如果(SendData的!= NULL){
          尝试 {
            如果(sendData.fileName!= NULL){
              布尔成功= FALSE;
              尝试 {
                HTT prequest请求= transport.buildPostRequest();
                request.url = GdocUrl.relativeToRoot(
                    默认/私营/已满);
                Toast.makeText(上下文,request.url.toString(),Toast.LENGTH_LONG).show();
                ((GoogleHeaders)request.headers).setSlugFromFileName(
                    sendData.fileName);
                InputStreamContent内容=新InputStreamContent();
                content.inputStream =
                    。getContentResolver()openInputStream(sendData.uri);
                content.type = sendData.contentType;
                content.length = sendData.contentLength;
                request.content =内容;
                。request.execute()忽略();
                成功= TRUE;
              }赶上(IOException异常E){
                handleException(E);
              }
              setListAdapter(新ArrayAdapter<字符串>(这一点,
                  android.R.layout.simple_list_item_1,
                  新的String [] {成功? OK:错误}));
            }
          } 最后 {
            送出数据= ​​NULL;
          }
        } 其他 {
         executeRefreshAlbums();
        }
      }

      私人无效executeRefreshAlbums(){
            的String [] albumNames;
            名单< AlbumEntry>专辑= this.albums;
            albums.clear();
            尝试 {
              GdocUrl URL = GdocUrl.relativeToRoot(默认/私营/已满);
              //通过结果页
              而(真){
                UserFeed userFeed = UserFeed.executeGet(运输,URL);
                this.postLink = userFeed.getPostLink();
                如果(userFeed.albums!= NULL){
                  albums.addAll(userFeed.albums);
                }
                串NEXTLINK = userFeed.getNextLink();
                如果(NEXTLINK == NULL){
                  打破;
                }
              }
              INT numAlbums = albums.size();
              albumNames =新的String [numAlbums]
              的for(int i = 0; I< numAlbums;我++){
                albumNames [I] = albums.get(我).title伪;
              }
            }赶上(IOException异常E){
                Toast.makeText(上下文,e.getMessage(),Toast.LENGTH_LONG).show();
              handleException(E);
              albumNames =新的String [] {e.getMessage()};
              albums.clear();
            }
            setListAdapter(新ArrayAdapter<字符串>(
                此,android.R.layout.simple_list_item_1,albumNames));
            Toast.makeText(上下文,albumNames.toString(),Toast.LENGTH_LONG).show();
          }

      私人无效setLogging(布尔记录){
        Logger.getLogger(com.google.api.client)。执行setLevel(
            日志记录? Level.CONFIG:Level.OFF);
        共享preferences设置= getShared preferences(preF,0);
        布尔currentSetting = settings.getBoolean(记录,假);
        如果(currentSetting!=记录){
          共享preferences.Editor编辑器= settings.edit();
          editor.putBoolean(记录,记录);
          editor.commit();
        }
      }

      私人无效handleException(例外五){
        e.printStackTrace();
        共享preferences设置= getShared preferences(preF,0);
        布尔数= settings.getBoolean(记录,假);
        如果(E的instanceof的Htt presponseException){
          HTT presponse响应=((HTT presponseException)E).response;
          INT状态code = response.status code;
          尝试 {
            response.ignore();
          }赶上(IOException异常E1){
            e1.printStackTrace();
          }
          如果(状态code == 401 ||状态code == 403){
            gotAccount(真正的);
            返回;
          }
          如果(对数){
            尝试 {
              Log.e(TAG,response.parseAsString());
            }赶上(IOException异常ParseException的){
              parseException.printStackTrace();
            }
          }
        }
        如果(对数){
          Log.e(TAG,e.getMessage(),E);
        }
      }
    }
 

GdocUrl

 包com.fetchgoogledocs;

进口com.google.api.client.googleapis.GoogleUrl;
进口com.google.api.client.util.Key;

/ **
 * @author的Yaniv因巴尔
 * /
公共类GdocUrl扩展GoogleUrl {

  公共静态最后弦乐ROOT_URL =htt​​ps://docs.google.com/feeds/;

  @键
  公共字符串类型的;

  公共GdocUrl(字符串连接codedUrl){
    超(EN codedUrl);
  }

  / **
   *构造基于给定的相对路径上的一个新的URL。
   *
   * @参数relativePath EN codeD路径相对于{@link #ROOT_URL}
   返回:新网址
   * /
  公共静态GdocUrl relativeToRoot(字符串relativePath){
    返回新GdocUrl(ROOT_URL + relativePath);
  }
}
 

Mainfest

 < XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
      包=com.google.api.client.sample.picasa
      安卓版code =1
      机器人:VERSIONNAME =1.0>
    <使用-SDK安卓的minSdkVersion =7/>

 <使用-权限的Andr​​oid:名称=android.permission.INTERNET对/>
  <使用-权限的Andr​​oid:名称=android.permission.GET_ACCOUNTS/>
  <使用-权限的Andr​​oid:名称=android.permission.USE_CREDENTIALS/>
  <使用-权限的Andr​​oid:名称=android.permission.MANAGE_ACCOUNTS/>
  <应用机器人:图标=@可绘制/图标机器人:标签=@字符串/ APP_NAME
    机器人:可调试=真正的>
    <活动机器人:PicasaDemoActivity名称=机器人:标签=@字符串/ APP_NAME>
      <意向滤光器>
        <作用机器人:名称=android.intent.action.MAIN/>
        <类机器人:名称=android.intent.category.LAUNCHER/>
      &所述; /意图滤光器>
      <意向滤光器>
        <作用机器人:名称=android.intent.action.SEND>< /作用>
        <类机器人:名称=android.intent.category.DEFAULT>< /类>
        <数据机器人:MIMETYPE =图像/ *>< /数据>
      &所述; /意图滤光器>
    < /活性GT;
    < /用途>
< /舱单>
 

UserFeed

 进口com.google.api.client.http.HttpTransport;
进口com.google.api.client.util.Key;

进口java.io.IOException异常;
进口的java.util.List;

公共类UserFeed扩展了进纸{

  @key(输入)
  公开名单< AlbumEntry>专辑;

  公共静态UserFeed executeGet(HttpTransport运输,GdocUrl URL)
      抛出IOException异常{
    url.kinds =专辑;
    返回(UserFeed)Feed.executeGet(运输,网址,UserFeed.class);
  }
}
 

频道

 进口com.google.api.client.googleapis.xml.atom.GData;
进口com.google.api.client.http.Htt prequest;
进口com.google.api.client.http.HttpTransport;
进口com.google.api.client.util.Key;

进口java.io.IOException异常;
进口的java.util.List;

/ **
 * @author的Yaniv因巴尔
 * /
公共类饲料{

  @key(链接)
  公开名单<链接>链接;

  公共字符串getPostLink(){
    返回Link.find(链接,http://schemas.google.com/g/2005#post);
  }

  公共字符串getNextLink(){
    返回Link.find(链接,下一步);
  }

  静态饲料executeGet(HttpTransport运输,GdocUrl网址,
      类和LT ;?延长饲料> feedClass)抛出IOException异常{
    url.fields = GData.getFieldsFor(feedClass);
    HTT prequest请求= transport.buildGetRequest();
    request.url =网址;
    。返回request.execute()parseAs(feedClass);
  }
}
 

我想我的问题就出在订阅 Userfeed 类,因为我不知道放什么下一个网址

解决方案

您需要设置的版本。从所谓的指定版本 ...

  

如果你犯了一个请求,使用只适用于功能的API   第3版,却忘了设定的版本,你很可能会得到   一个400错误的请求的响应。由于URL结构是不同的   版本2和3之间,这是由新的用户所做的一个常见的​​错误   的API。

     

要指定一个版本号,使用的GData-Version的HTTP标头。该   这个头的值必须是3.0。小数和零是   必需的。

 的GData-版本:3.0
 

  

另外,你可以指定V = 3作为URL中的查询参数。   这是一个防火墙,它删除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

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

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