【发布时间】:2015-12-16 03:49:14
【问题描述】:
我在将 GCM 注册 ID 添加到我的 Android 应用中的设备组客户端时遇到问题。我已按照https://developers.google.com/cloud-messaging/android/client-device-group 的所有说明进行操作,但不断收到 401 HTTP 响应。我找到了以下帖子,但没有人有答案...
- get notification key error 401 gcm https://android.googleapis.com/gcm/googlenotification
- Google Cloud Messaging, returning 401 Unauthorized
- Google Cloud Messaging, 401 Unauthorized is returned when creating notification key from client
- How to successfully "Generate a Notification Key on the Client" with GCM?
我已成功从 GoogleSignInApi 和 Google 说明中提供的方法获取身份验证令牌,但都返回 401 响应。我已确保在我的 Google 开发者控制台中将客户端 ID 用于 Web 应用程序,但仍然没有运气。这是我的代码 sn-p...
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
// HTTP request header
con.setRequestProperty("project_id", getString(R.string.gcm_defaultSenderId));
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
String accountName = getAccount();
//Initialize the scope using the client ID you got from the Console.
final String scope = "audience:server:client_id:"
+ "MY_WEB_APP_CLIENT_ID";
String idToken = "";
try {
idToken = GoogleAuthUtil.getToken(this, sharedPref.getString("googleEmail", ""), scope);
} catch (Exception e) {
e.printStackTrace();
}
// HTTP request
JSONObject data = new JSONObject();
data.put("operation", "add");
data.put("notification_key_name", "my_group_name");
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId)));
data.put("id_token", idToken);
OutputStream os = con.getOutputStream();
os.write(data.toString().getBytes("UTF-8"));
os.close();
int responseCode = con.getResponseCode();
我认为这个 HTTP 发布请求并不重要,但我还确保正确的项目和客户端 ID (android) 存储在我的 google-services.json 中。有没有人成功管理设备组客户端?如果是这样,我的代码与您的代码有何不同?
【问题讨论】:
-
在设备组点击这里尝试这个官方 repo:github.com/google/gcm/tree/master/samples/android/gcm-demo 并获取一些想法
-
不幸的是,该演示使用了使用 API 密钥的服务器端方法。出于安全原因,我想避免在客户端上使用该密钥。
-
我也遇到了同样的问题,你找到解决办法了吗?
-
看起来 notification_key_name 需要是获取您的 id_token 的用户的电子邮件,请参阅this answer。
标签: android google-cloud-messaging