java - 如何在 android 中为 google api 交换 OAuth2 token 的授权码?

标签 java android authorization oauth-2.0

如何在 android 中为 google api 交换 OAuth2 token 的授权码?如果你去 https://code.google.com/oauthplayground/您可以交换它们,但我需要能够在 Android 应用程序中进行交换!有什么想法吗?

最佳答案

我自己发现的! :)

您需要做的就是使用授权码、客户端 ID、客户端密码、redirect_uri 和授权类型向 accounts.google.com/o/oauth2/token 发送一个 HttpPost!我将代码添加到答案中,这样您就可以看到如何准确地做到这一点!希望对你有帮助

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

关于java - 如何在 android 中为 google api 交换 OAuth2 token 的授权码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11092340/

相关文章:

java - 打印具有 5 个最高值的 key

java - 进程 'command ' C :/Users/xxxx/python. exe'' 已完成,退出值非零 1

firebase - Firestore - 授予对子集合的访问权限也会授予对父集合的访问权限?

c# - ASP MVC C# : Is it possible to pass dynamic values into an attribute?

node.js - Github Web API 授权问题 - 返回 "Not found"

java - Java 7 异步 NIO2 服务器上的连接被拒绝

java - VSCode : The package is accessible from more than one module

java - Spring-Boot:依赖注入(inject)取决于配置(和使用接口(interface))

java - 获取对象在 Java 列表中的索引

Android:读取原始类型并将其写入内部存储