Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

oauth 2.0 - Google Cloud Messaging (GCM) with local device groups on Android gives HTTP Error code 401

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. "[email protected]"
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...