import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.io.OutputStream;
import
java.net.URL;
import
java.util.HashMap;
import
javax.net.ssl.HttpsURLConnection;
import
org.apache.http.HttpStatus;
import
org.json.JSONException;
import
org.json.JSONObject;
/**
* @author athakur
*/
public
class
FCMMessageSender {
public
static
final
String FCM_SERVER_API_KEY =
"<ADD_YOUR_SERVER_API_KEY>"
;
private
static
final
String deviceRegistrationId =
"<ADD_YOUR_DEVICE_REG_ID>"
;
public
static
void
main(String args[])
{
int
responseCode = -
1
;
String responseBody =
null
;
try
{
System.out.println(
"Sending FCM request"
);
byte
[] postData = getPostData(deviceRegistrationId);
URL url =
new
URL(FCM_URL);
HttpsURLConnection httpURLConnection = (HttpsURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(
10000
);
httpURLConnection.setReadTimeout(
10000
);
httpURLConnection.setDoOutput(
true
);
httpURLConnection.setUseCaches(
false
);
httpURLConnection.setRequestMethod(
"POST"
);
httpURLConnection.setRequestProperty(
"Content-Type"
,
"application/json"
);
httpURLConnection.setRequestProperty(
"Content-Length"
, Integer.toString(postData.length));
httpURLConnection.setRequestProperty(
"Authorization"
,
"key="
+FCM_SERVER_API_KEY);
OutputStream out = httpURLConnection.getOutputStream();
out.write(postData);
out.close();
responseCode = httpURLConnection.getResponseCode();
if
(responseCode == HttpStatus.SC_OK)
{
responseBody = convertStreamToString(httpURLConnection.getInputStream());
System.out.println(
"FCM message sent : "
+ responseBody);
}
else
{
responseBody = convertStreamToString(httpURLConnection.getErrorStream());
System.out.println(
"Sending FCM request failed for regId: "
+ deviceRegistrationId +
" response: "
+ responseBody);
}
}
catch
(IOException ioe)
{
System.out.println(
"IO Exception in sending FCM request. regId: "
+ deviceRegistrationId);
ioe.printStackTrace();
}
catch
(Exception e)
{
System.out.println(
"Unknown exception in sending FCM request. regId: "
+ deviceRegistrationId);
e.printStackTrace();
}
}
public
static
byte
[] getPostData(String registrationId)
throws
JSONException {
HashMap<String, String> dataMap =
new
HashMap<>();
JSONObject payloadObject =
new
JSONObject();
dataMap.put(
"name"
,
"Aniket!"
);
dataMap.put(
"country"
,
"India"
);
JSONObject data =
new
JSONObject(dataMap);;
payloadObject.put(
"data"
, data);
payloadObject.put(
"to"
, registrationId);
return
payloadObject.toString().getBytes();
}
public
static
String convertStreamToString (InputStream inStream)
throws
Exception
{
InputStreamReader inputStream =
new
InputStreamReader(inStream);
BufferedReader bReader =
new
BufferedReader(inputStream);
StringBuilder sb =
new
StringBuilder();
String line =
null
;
while
((line = bReader.readLine()) !=
null
)
{
sb.append(line);
}
return
sb.toString();
}
}