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