I am trying to send request to Firebase server for FCM and as FCM documentation says it should be POST request with JSON data. This is the sample.
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
So can anyone give the a proper code that will send POST request with this JSON data?
This is what I tried but it is not working
AsyncT.java
package com.example.artin.pushnotifications;
import android.os.AsyncTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
class AsyncT extends AsyncTask<Void,Void,Void> {
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send"); //Enter URL here
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
httpURLConnection.setRequestProperty("Authorization","key=AIzaSyDZx9l_Izta9AjVS0CX70ou8OjbDVVGlHo");
httpURLConnection.connect();
JSONObject jsonObject = new JSONObject();
JSONObject param = new JSONObject();
param.put("Hii","there");
jsonObject.put("data",param);
jsonObject.put("to", "dXazhmeFSSU:APA91bG23o75zeNOCb7pY-OCQG4BsGbY-YZrSnDrvLWv1");
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And I execute it when button is pressed
AsyncT asyncT = new AsyncT();
asyncT.execute();