Firebase云消息传递 - 设备组

时间:2017-04-03 15:44:22

标签: java firebase firebase-cloud-messaging

我尝试在Firebase云消息传递系统中创建一组设备,但我得到了一个ioexception" https://android.googleapis.com/gcm/googlenotification"。 我有几个问题:

  1. 我需要在字段中添加什么:senderId,registrationId,idToken?
  2. 如何更改此部分代码以创建组而不添加到组?
  3. 我需要放置"授权"," key = AIzaS ..."?
  4. 代码:

    public String addNotificationKey(
            String senderId, String userEmail, String registrationId, String idToken)
        throws IOException, JSONException {
        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", senderId);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod("POST");
        con.connect();
    
        // HTTP request
        JSONObject data = new JSONObject();
        data.put("operation", "add");
        data.put("notification_key_name", userEmail);
        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();
    
        // Read the response into a string
        InputStream is = con.getInputStream();
        String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
        is.close();
    
        // Parse the JSON string and return the notification key
        JSONObject response = new JSONObject(responseString);
        return response.getString("notification_key");
    
    }
    

2 个答案:

答案 0 :(得分:1)

对于#3:

con.setRequestProperty("Authorization", "key=AIzaS...");

答案 1 :(得分:0)

  
      
  1. 我需要在字段中添加什么:senderId,registrationId,idToken?
  2.   

Credentials中查看他们的定义。

可以在Firebase Console中找到发件人ID。转到项目设置,然后转到 Cloud Messaging 选项卡。

在您的客户端应用程序端生成注册令牌。请参阅相应的设置文档,具体取决于客户端应用类型here

idToken是(AFAIK)仅在客户端应用程序端使用。请参阅(Android)文档here

  
      
  1. 如何更改此部分代码以创建组而不添加到组?
  2.   

更改

data.put("operation", "add");

data.put("operation", "create");
  
      
  1. 我需要放“授权”,“key = AIzaS ......”?
  2.   

请参阅Puf's answer