youtube data api v3 android AbstractGoogleClientRequest.exec



我正在尝试在android应用程序上搜索youtube视频。我使用youtube数据api v3。我使用示例代码https://developers.google.com/youtube/v3/code_samples/java#search_by_keyword

我在这条线上得到一个例外:

// Call the API and print results.
SearchListResponse searchResponse = search.execute();

我的主要活动:

package com.yasin_alm.bestsongsplaylistsyoutube;
import java.io.IOException;
import java.util.List;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.astuetz.PagerSlidingTabStrip;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.OnInitializedListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
public class MainActivity extends ActionBarActivity implements OnInitializedListener {
    public static final String DEVELOPER_KEY="my api key from console.developer.com";
    public static final String TAG="bestsongs";
    private ViewPager pager;    
    private TabsPagerAdapter pagerAdapter;
    private PagerSlidingTabStrip tabs;
    private String searchQuery="pop songs";
    private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
    /**
     * Define a global instance of a Youtube object, which will be used
     * to make YouTube Data API requests.
     */
    private static YouTube youtube;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        doSearch();
        NowPlayingFragment nowPlayingFragmentFragment = NowPlayingFragment.newInstance("nCgQDjiotG0");
        //getSupportFragmentManager().beginTransaction().replace(R.layout.fragment_nowplaying, nowPlayingFragmentFragment).commit();
        // Initialise the ViewPager and set an adapter
        pager = (ViewPager) findViewById(R.id.pager_main);
        pager.setOffscreenPageLimit(3); //# of fragments loading
        pagerAdapter=new TabsPagerAdapter(getSupportFragmentManager(),getResources().getStringArray(R.array.tab_titles));
        pagerAdapter.add(nowPlayingFragmentFragment);
        pager.setAdapter(pagerAdapter);
        // Bind the tabs to the ViewPager
        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        tabs.setViewPager(pager);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onInitializationFailure(Provider provider,
            YouTubeInitializationResult error) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
            boolean wasRestored) {
        if (!wasRestored) {
            player.cueVideo("nCgQDjiotG0");
        }
    }
    /**
     * Initialize a YouTube object to search for videos on YouTube. Then
     * display the name and thumbnail image of each video in the result set.
     *
     * @param args command line args.
     */
    public void doSearch() {
        try {
            // This object is used to make YouTube Data API requests. The last
            // argument is required, but since we don't need anything
            // initialized when the HttpRequest is initialized, we override
            // the interface and provide a no-op function.
            youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
                public void initialize(HttpRequest request) throws IOException {
                }
            }).setApplicationName("BestSongsPlaylistsYoutube").build();
            Log.d(TAG, "a");
            // Define the API request for retrieving search results.
            YouTube.Search.List search = youtube.search().list("id,snippet");
            // Set your developer key from the Google Developers Console for
            // non-authenticated requests. See:
            // https://console.developers.google.com/
            search.setKey(DEVELOPER_KEY);
            search.setQ(searchQuery);
            // Restrict the search results to only include videos. See:
            // https://developers.google.com/youtube/v3/docs/search/list#type
            search.setType("video");
            // To increase efficiency, only retrieve the fields that the
            // application uses.
            search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
            search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
            Log.d(TAG, "b");
            // Call the API and print results.
            SearchListResponse searchResponse = search.execute();
            Log.d(TAG, "c");
            List<SearchResult> searchResultList = searchResponse.getItems();
            if (searchResultList != null) {
                //prettyPrint(searchResultList.iterator(), queryTerm);
                Log.d(TAG,"video: "+searchResultList.get(0).getId().getVideoId());
            }
        } catch (GoogleJsonResponseException e) {
            Log.e(TAG,"There was a service error: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());
        } catch (IOException e) {
            Log.e(TAG,"IOException: " + e.getCause() + " : " + e.getMessage() +" : "+ e.getLocalizedMessage());
            e.printStackTrace();
        } 
    }
}

我的logcat输出:

08-30 01:55:14.659: D/bestsongs(14223): a
08-30 01:55:14.689: D/bestsongs(14223): b
08-30 01:55:14.726: E/bestsongs(14223): IOException: null : null : null

我检查了类似的问题,我已经:

  • 尝试了服务器应用程序的Key,而不是Android应用程序的密钥
  • 尝试了浏览器应用程序的Key,而不是Android应用程序的密钥
  • 已检查sha1和包名称

有什么建议吗?我想做的就是在我的android应用程序中搜索youtube上的视频。提前谢谢。

已解决:您需要使用浏览器键访问Youtube Data API。Android密钥仅用于Youtube Player。

此外:

你可以尝试删除你的项目,并在谷歌开发者控制台上从头开始重置所有内容。

我在一个异步任务中实现了搜索功能。

相关内容

  • 没有找到相关文章

最新更新