Last active
October 14, 2019 04:26
-
-
Save anta40/76d2b7a085b3c460bfa73c5777f69cb3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
public static String sendToTopic(String topicName, String messageBody) throws IOException, JSONException { | |
String result = ""; | |
URL url = new URL(API_URL_FCM); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setUseCaches(false); | |
conn.setDoInput(true); | |
conn.setDoOutput(true); | |
conn.setRequestMethod("POST"); | |
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM); | |
conn.setRequestProperty("Content-Type", "application/json"); | |
JSONObject jsObj = new JSONObject(); | |
JSONObject oNotif = new JSONObject(); | |
jsObj.put("to", "/topics/"+ topicName); | |
JSONObject oData = new JSONObject(); | |
oData.put("message", messageBody); | |
jsObj.put("data", oData); | |
try { | |
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); | |
wr.write(jsObj.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 = "OK"; | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
result = "BAD"; | |
} | |
System.out.println("GCM Notification is sent successfully"); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment