我按照 这份文件 获得了授权码。但是当我试图获取访问令牌时,我总是会出错。谁能帮我 ?
public String AccessToken()
{
String accessToken = "";
StringBuilder strBuild = new StringBuilder();
String authURL = "https://accounts.google.com/o/oauth2/token?";
String code = "4/SVisuz_x*********************";
String client_id = "******************e.apps.googleusercontent.com";
String client_secret = "*******************";
String redirect_uri = "urn:ietf:wg:oauth:2.0:oob";
String grant_type="authorization_code";
strBuild.append("code=").append(code)
.append("&client_id=").append(client_id)
.append("&client_secret=").append(client_secret)
.append("&redirect_uri=").append(redirect_uri)
.append("&grant_type=").append(grant_type);
System.out.println(strBuild.toString());
try{
URL obj = new URL(authURL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Host", "www.googleapis.com");
//BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
//bw.write(strBuild.toString());
//bw.close();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(strBuild.toString());
wr.flush();
wr.close();
//OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
System.out.println(con.getResponseCode());
System.out.println(con.getResponseMessage());
} catch (Exception e)
{
System.out.println("Error.");
}
return "";
}
当我运行这段代码时,输出是: 400
Bad Request
原文由 tqjustc 发布,翻译遵循 CC BY-SA 4.0 许可协议
答: 根据 您的以下教程,您正在使用
OAuth 2.0
。因此,有一个使用OAuth 2.0
访问 Google API 的基本模式。它遵循 4 个步骤:具体可以参考教程- 使用OAuth 2.0访问Google APIs
您必须访问 Google Developers Console 以获得 OAuth 2.0 凭据,例如 Google 和您的应用程序都知道的
client ID
和client secret
根本原因分析:
问题 1:
研究你的代码后,发现了一些不足。如果你的代码运行顺利,那么代码总是给出一个空字符串。因为你的
AccessToken()
方法总是返回return "";
问题 2:
您的 try catch 块将成为异常块。因为,您似乎没有正确完成代码。您错过了
encoding
以及使用准备访问令牌的JSONObject
。所以它给出的输出是解决方案:
我知道您的代码与本 教程 相似
由于您的代码需要更多更改才能解决您的问题。所以我建议您使用 LinkedHashMap 或 ArrayList 。这些将提供更简单的解决方案。所以我给你 2 个示例代码,让你的生活更轻松。您可以选择其中任何一个。您需要将
refresh_token, client id, client secret and grant type
更改为您的。资源链接:
无法从 Google Play Android Developer API 获取订阅信息
使用 java.net.URLConnection 触发和处理 HTTP 请求
如何在 Java 中发送 HTTP 请求 GET/POST
希望这个
samples
和resource link
将帮助您解决问题并获得access token
的访问权限。什么是400错误请求?
Ans: 表示查询无效。父 ID 缺失或请求的维度或指标组合无效。
建议的操作: 您需要更改 API 查询才能使其正常工作。
为什么令牌会过期?令牌的限制是多少?
由于以下原因之一,令牌可能会停止工作:
revoked
访问权限。six months
。user changed passwords
和令牌包含 Gmail、日历、联系人或环聊范围。exceeded a certain number of token requests
。有
currently a limit of 25 refresh tokens per user account per client
。如果达到限制,创建新令牌会自动使最旧的令牌失效,而不会发出警告。此限制不适用于服务帐户。应遵循哪些预防措施?
注意事项 - 1:
注意事项 - 2:
注意事项 - 3: