你如何在android中为谷歌api交换OAuth2令牌的授权代码?

Wil*_* L. 2 java android authorization oauth-2.0

你如何在android中为谷歌api交换OAuth2令牌的授权代码?如果你去https://code.google.com/oauthplayground/你可以交换它们,但我需要能够在Android应用程序中做到这一点!有任何想法吗?

Wil*_* L. 9

我发现了自己!:)

您需要做的就是使用授权码,客户端ID,客户端密码,redirect_uri和授权类型将HttpPost发送到accounts.google.com/o/oauth2/token!我将代码添加到答案中,以便您可以看到如何完成!希望能帮助到你

HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("code", "<your_auth_code>"));
        pairs.add(new BasicNameValuePair("client_id", "<your_client_id>"));
        pairs.add(new BasicNameValuePair("client_secret", "<your_client_secret>"));
        pairs.add(new BasicNameValuePair("redirect_uri", "<your_redirect_uri>"));
        pairs.add(new BasicNameValuePair("grant_type", "authorization_code")); //Leave this line how it is   
        post.setEntity(new UrlEncodedFormEntity(pairs));
        org.apache.http.HttpResponse response = client.execute(post);
        String responseBody = EntityUtils.toString(response.getEntity());
        Log.v("message", responseBody); // That just logs it into logCat
Run Code Online (Sandbox Code Playgroud)

  • 这是非常不好的做法,因为它暴露了Android代码中的客户端秘密,使您的应用程序容易受到冒充.理想情况下,您应该在自己的服务器上使用服务器端Web服务,以便保持client_secret的秘密! (2认同)