I am trying to get Google Cloud Messaging (GCM) to work on Android with local device groups as described on https://developers.google.com/cloud-messaging/android/client-device-group .
I have enabled the following services in the web console ( https://console.developers.google.com ):
- Google Cloud Messaging for Android
- Google Cloud Pub/Sub
- Google+ API
I have also created the following credentials:
- API key (with specified package name and SHA-1 certificate keyprint)
- OAuth 2.0 client IDs (Web application)
My Android code looks as follows (error handling etc. has been stripped):
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
The submitted JSON to https://android.googleapis.com/gcm/notification looks something like this:
{
"operation": "add",
"notification_key_name": "foobar",
"registration_ids": ["42","44"],
"id_token": "[veeeeeery long string]"
}
The response contents is:
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
What am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…