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());
}
When I call the above code, it gives me response as 401 Unauthorized
. I am not able to understand why I am getting this error. I have used proper server key. Is there any syntax error or anything wrong in the strategy used by me.
I have followed the https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol documentation
https://firebase.google.com/docs/cloud-messaging/server
"Make sure this is the server key, whose value is available in the Cloud Messaging tab of the Firebase console Settings pane. Android, iOS, and browser keys are rejected by FCM."
Try replacing:
with:
Just Solved the problem for me, I changed the Server API Key, which is given on the Cloud messaging tab, in FCM Console. In Project Overview, Manage, there is the Cloud Messaging tab, it shows a SERVER API KEY use that may be. In json file client_api key and SERVER_API_KEY different!!
Based on Harco's answer, in the Firebase console look at "Project settings" (click on gear icon) and choose the "Cloud Messaging" tab. "Server key" is what you need.
Actual on 2017.06.28.