I am trying to send notification to registered devices using gcm. But it send "null" instead of message. I have tried lot of solutions. If any basic thing is missing kindly share. I have attached the code spinet.
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
String msg = "new order came";
jData.put("message", msg);
// Where to send GCM message.
if (!(id == null)) {
jGcmData.put("to", id);
} else {
jGcmData.put("to", "/topics/global");
}
// What to send in GCM message.
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + API_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
The url you are using is incorrect. It should be https://gcm-http.googleapis.com/gcm/send. See Server changes.
Related
I am trying to send HTTP PUT request to Cloudant database to update a key "BPInc" to "N". Its current value is "Y". I am using HTTPURLConnection to make the connection and send request. I am able to send GET request successfully and retrieve the BPInc value. But when I am sending the PUT request, I am getting error code - 400.
I have also looked into cloudant-client library, but not able to get how to send PUT request and I want to stick to HTTPURLConnection method only.
Here's the code ,
// After retrieving _rev and _id using GET request......
String revID = "_rev of the document";
String docID = "_id of the document";
URL postUrl = new URL("<Cloudant URL>/<DB NAME>/" + docID);
String usernameColonPassword = "<API KEY>:<PASSWORD>";
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
HttpURLConnection conn = (HttpURLConnection)postUrl.openConnection();
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", basicAuthPayload);
conn.setDoOutput(true);
OutputStreamWriter json = new OutputStreamWriter(conn.getOutputStream());
json.write(String.format("{\"_rev\":revID, \"BPInc\":\"Y\"}"));
json.flush();
json.close();
int putResponseCode = conn.getResponseCode();
I am very new to this so I suppose I might be doing wrong something. Please suggest.
This question already has an answer here:
How to track FCM push notifications send form server side or Rest Client? [duplicate]
(1 answer)
Closed 5 years ago.
Here is my code that I am attempting to set up a firebase call to send a message to a topic. I get a 200 response code back but nothing appears on the FCM console. Am i doing something wrong.
public static void pushFCMNotification() throws Exception{
String authKey = Constants.AUTH_KEY_FCM;
String FMCurl = Constants.API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
JSONObject info = new JSONObject();
try {
info.put("title", "New notification"); // Notification title
info.put("body", "A new notification has been added to the notice board"); // Notification body
json.put("notification", info);
json.put("to", "/topics/notif"); //replace userDeviceIdKey with the unique notification key for the group
} catch (JSONException e) {
e.printStackTrace();
}
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}
Thanks for the help in advance.
Messages sent through the REST API don't appear in the console (regardless if it's sent to a token or to a topic).
Usually, if you use the REST API to send to a token, you could view it in the Diagnostics Page. However, messages sent to topics don't appear there as well. (see the Possible duplicate post I linked in the comments section)
I am trying to connect to firebase to send push notification to an android app.
I have written following code in Java Server side. But I am getting connection timed out exception always.
final String apiKey="AAAAeEpqP-w:APA91bFulyT23Km-onTNr_q5yEz4uoOaM8KdE4LMyIoz6kWlk3pJSHirDJBSiqESRXKiGa-Z_tBfpXA6naaaTXxcFFxAnaSkMTPVVOMswyJ0bhhdpwlo-92HXgxRMsHV6Y8bNaHX7tMd";
int i=0;
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection ) url.openConnection();
System.out.println("after connection open");
//conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
JSONObject json = new JSONObject();
json.put("to", "device-token");
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body");
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
// result = CommonConstants.SUCCESS;
System.out.println("after closed out put stream");
int responseCode = conn.getResponseCode();
// System.out.println("Post parameters : " + input);
System.out.println("Response Code : " + responseCode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
It always shows session timeout error.
Is it a correct way to send notifications to app.
Any help is appreciated.
EDIT :- I have called the same url with device token and other things from rest client and it works well.I got a notification in my app.But when i send it thru Java code at that time it shows connection timed out.
Here's the official Firebase documentation which can help you set up the server. https://firebase.google.com/docs/cloud-messaging/server
In your code I noticed json.put("to", "device-token"); and I am assuming that you are using it as a placeholder only for the example. If not, in your request you need to send a device-token like { "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } .
I am new to user java to connect to server. I have succeed in forming a json which has some key and value to form the body to call the api service and get successful response (with the following code).
My questions are:
Some of my web service just request header info, for example, I just need to
put the ApiKey(key name) and key value in the header and send to server, no other info is needed in body, how can I do this?
Some of my web service require both header info and body info, how can I construct the json and send to server?
try {
String input = jsonString;
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
System.out.println("errorcode" + conn.getResponseCode());
if (conn.getResponseCode() != 200) {
JOptionPane.showMessageDialog(new JFrame(), "Please input a correct username or password");
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String jsonText = read(br);
System.out.println("jsonText: " + jsonText);
I am using gcm to push notifications to one or multiple devices, However I constantly get the error message: "mismatched sender ID".
Here is my code:
public static void post(String apiKey){
try{
// prepare JSON
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("message", "{good luck}");
jGcmData.put("to","token ID");
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
// Read GCM response.
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
} catch (IOException e) {
System.out.println("Unable to send GCM message. "+e);
}
}
Also, when I used jGcmData.put("to","/topics/foo-bar");instead of jGcmData.put("to","token ID");, the notification can be sent successfully. However what I want is to push notification to selected devices.
For the mismatched sender ID:
Try uninstalling the app and run it again.This will clear any created keys of the App.
error:MismatchSenderId
A registration token is tied to a certain group of senders. When a client app registers for GCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work.
According to this SO answer, ""mismatchSenderId happens because the app within the same device have logged with different keys.""
For the Topic Subscription / Topic Sending
This may be related to this Subscribe to topics suddenly throws "java.io.IOException: InternalServerError", it says that "We identified an issue in our backed that affected a small percentage of the topic subscriptions during the last 24 hours. The issue has already been fixed, and the subscriptions should work correctly on all devices."
I hope this helps you.