【发布时间】:2016-03-10 00:02:30
【问题描述】:
我正在尝试让 Google Cloud Messaging (GCM) 在 Android 上使用https://developers.google.com/cloud-messaging/android/client-device-group 中所述的本地设备组工作。
我在 Web 控制台 (https://console.developers.google.com) 中启用了以下服务:
- 适用于 Android 的 Google 云消息传递
- 谷歌云发布/订阅
- Google+ API
我还创建了以下凭据:
- API 密钥(带有指定的包名称和 SHA-1 证书密钥)
- OAuth 2.0 客户端 ID(Web 应用程序)
我的 Android 代码如下所示(错误处理等已被剥离):
String account = ACCOUNT_NAME; // E.g. "johndoe@google.com"
String scope = "audience:server:client_id:" + WEB_APPLICATION_CLIENT_ID;
String token = GoogleAuthUtil.getToken(context, account, scope);
// Token is successfully found here :-)
URL url = new URL("https://android.googleapis.com/gcm/notification");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("project_id", NUMERICAL_PROJECT_ID);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
JSONObject requestBody = new JSONObject();
requestBody.put("operation", "add");
requestBody.put("notification_key_name", "foobar");
requestBody.put("registration_ids",
new JSONArray(Arrays.asList(new String[]{"42", "44"})));
requestBody.put("id_token", token);
OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();
// connection.getResponseCode() is now 401
提交给https://android.googleapis.com/gcm/notification 的 JSON 如下所示:
{
"operation": "add",
"notification_key_name": "foobar",
"registration_ids": ["42","44"],
"id_token": "[veeeeeery long string]"
}
响应内容为:
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
我做错了什么?
【问题讨论】:
-
为了确定,已经运行了来自developers.google.com/cloud-messaging/android/start的第4部分示例
-
很明显,您已经付出了彻底的努力来完成这项工作。我也尝试过,但失败了。对于同一问题还有另外两个 SO 问题,one recent 和 the other 来自一年前。两者都没有解决办法。 instructions 显然是错误的或不完整的。非常沮丧!
-
是的。我从示例开始并尝试将其移动到本地设备组,因为我不希望在解决方案架构中有不必要的应用服务器。这些示例假设您有一个可用的应用服务器。
标签: android oauth-2.0 google-cloud-messaging