private void sendMsg() {
DBManager dbManager = DBManager.getInstance();
ArrayList<String> firebaseIds;
try {
ResultSet rs= dbManager.getRegisteredFirebaseDevice();
while(rs.next()){
System.out.println(rs.getString(1));
firebaseIds.add(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
String url = "https://fcm.googleapis.com/fcm/send";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Authorization: key", "AIzaSyAl6S936qt_NKKFwwbd-NEmiSGIL7G_yJc");
con.setRequestProperty("Content-Type", "application/json");
// String msg="New design added in "+getCategory(designCategory)+". Design no."+designNo;
// String urlParameters = "data.msg="+msg+"®istration_id="+firebaseIds.get(0);
JSONObject msg=new JSONObject();
msg.put("msg","New design added in "+getCategory(designCategory)+". Design no."+designNo);
JSONObject parent=new JSONObject();
parent.put("to", firebaseIds.get(0));
parent.put("data", msg);
// String urlParameters = "registration_id="+firebaseIds.get(0);
// Send post request
con.setDoOutput(true);
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
// DataOutputStream wr = new DataOutputStream(con.getOutputStream());
// wr.writeBytes(urlParameters);
// wr.flush();
// wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + parent.toString());
System.out.println("Response Code : " + responseCode+" "+con.getResponseMessage());
}
当我调用上面的代码时,它会给我回复401 Unauthorized
。我无法理解为什么会收到此错误。我使用了正确的服务器密钥。在我使用的策略中是否存在语法错误或任何错误。
我已按照https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol文档
进行操作答案 0 :(得分:11)
刚刚为我解决了这个问题,我在FCM控制台中更改了云消息传递选项卡上的服务器API密钥。在项目概述,管理中,有云消息传递选项卡,它显示可能的SERVER API KEY使用。在json文件中client_api键与SERVER_API_KEY不同!!
答案 1 :(得分:8)
尝试更换:
con.setRequestProperty("Authorization: key", "<YOUR API KEY>");
使用:
con.setRequestProperty("Authorization", "key=<YOUR API KEY>");
答案 2 :(得分:3)
根据 Harco 的答案,在Firebase控制台中查看&#34;项目设置&#34; (点击齿轮图标),然后选择&#34;云消息传递&#34;标签。 &#34;服务器密钥&#34;是你需要的。
2017.06.28实际。
答案 3 :(得分:-1)
https://firebase.google.com/docs/cloud-messaging/server
“确保这是服务器密钥,其值在Firebase控制台”设置“窗格的”云消息传递“选项卡中可用。安全,iOS和浏览器密钥被FCM拒绝。”