【问题标题】:Using OAuth2 to access YouTube api in AndroidAndroid中使用OAuth2访问YouTube api
【发布时间】:2013-06-01 07:14:05
【问题描述】:

我正在开发一个应用程序,该应用程序应该可以从用户的 YouTube 帐户中获取分析数据。 我可以在我的应用程序的 web 视图中使用以下 url 从 Google 检索授权代码。

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/yt-analytics.readonly&approval_prompt=force&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=762546229188.apps.googleusercontent.com&access_type=offline

我从页面标题中检索代码,然后使用 Java 的 substring 方法切断成功。 但是,当我去获取访问令牌时,它只会返回"error" : "invalid_grant"

        HttpClient client = new DefaultHttpClient(); //new HTTP client
        HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token"); //where to post to
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(); //construct the values to hand to Google
        Log.v("KUZMA", arg0[0]); //personal logcat message
        pairs.add(new BasicNameValuePair("code", arg0[0])); //in arg0[0] lives the auth code
        pairs.add(new BasicNameValuePair("client_id", CLIENT_ID)); //I store the Client_id as a static variable at the beginning of my class
        //Log.v("Kuzma", CLIENT_ID);
        //pairs.add(new BasicNameValuePair("client_secret", "*******"));
        pairs.add(new BasicNameValuePair("redirect_uri", "http://localhost"));
        pairs.add(new BasicNameValuePair("grant_type", "authorization_code")); //Leave this line how it is   
        String responseBody = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(pairs));
            org.apache.http.HttpResponse response = client.execute(post);
            responseBody = EntityUtils.toString(response.getEntity());
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.v("KUZMA", responseBody); // That just logs it into logCat
        //output.setText("something happened?");
        return null;

所以我想我最大的问题是我没有客户端密码,但谷歌没有为已安装的应用程序提供给我。有没有解决的办法?我也玩过 Google Play Services,但也无法正常工作,但如果你知道它是如何工作的,那就太好了!

【问题讨论】:

    标签: java android oauth-2.0 google-oauth


    【解决方案1】:

    虽然你不说,但它看起来像一个 Android 应用程序。因此,您需要使用 GoogleAuthUtil 为您提供范围的令牌;从这里开始:http://developer.android.com/google/play-services/auth.html

    【讨论】:

    • 是的,我应该回来并说我想通了,但是 5 点钟左右滚动,我完成了 :) 我将 GoogleAuthUtil 与 AccountPicker 结合使用来生成和使用令牌。谢谢。此外,我确实在标题和标签中提到了 Android。我认为这很清楚,但再次感谢。
    猜你喜欢
    • 2018-05-26
    • 2014-11-19
    • 2020-11-10
    • 2013-05-03
    • 2021-06-15
    • 2013-12-18
    • 2017-12-10
    • 2016-07-20
    • 2012-12-20
    相关资源
    最近更新 更多