我正在尝试让 Google Cloud Messaging (GCM) 在 Android 上与本地设备组一起使用,如上所述https://developers.google.com/cloud-messaging/android/client-device-group https://developers.google.com/cloud-messaging/android/client-device-group .
我已在 Web 控制台中启用了以下服务(https://console.developers.google.com https://console.developers.google.com ):
- 适用于 Android 的 Google 云消息传递
- 谷歌云发布/订阅
- 谷歌+ API
我还创建了以下凭据:
- API 密钥(具有指定的包名称和 SHA-1 证书密钥)
- OAuth 2.0 客户端 ID(Web 应用程序)
我的 Android 代码如下所示(错误处理等已被删除):
String account = ACCOUNT_NAME; // E.g. "[email protected] /cdn-cgi/l/email-protection"
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
提交的 JSON 到https://android.googleapis.com/gcm/notification https://android.googleapis.com/gcm/notification看起来像这样:
{
"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>
我究竟做错了什么?