Skip to content

Instantly share code, notes, and snippets.

@AnanthaRajuC
Forked from Krishan14sharma/GcmMockServer.java
Created July 24, 2016 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnanthaRajuC/8e1874df62667bb8d93af4061cb441cd to your computer and use it in GitHub Desktop.
Save AnanthaRajuC/8e1874df62667bb8d93af4061cb441cd to your computer and use it in GitHub Desktop.
GCM Mock server code
package com.dnn.zapbuild.dnn.helper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A very simple program which pretends to be a "server" in that it sends
* a notification to the Google Cloud Messaging Server to cause it to send
* a message to our GCM Client.
* @author Ian Darwin, http://androidcookbook.com/
*/
public class GcmMockServer {
/** Confidential Server API key gotten from the Google Dev Console ->
* Credentials -> Public API Access -> Key for Android Apps */
final static String AUTH_KEY=""; // set in a static initializer, not shown, key for
final static String POST_URL = "https://android.googleapis.com/gcm/send";
public static void main(String[] args) throws Exception {
final String[][] MESSAGE_HEADERS = {
{"Content-Type", "application/json"},
{ "Authorization", "key=" + AUTH_KEY}
};
String regIdFromClientApp = ""; // has to be set somehow!
String jsonMessage =
"{\n" +
" \"registration_ids\" : [\""+ regIdFromClientApp + "\"],\n" +
" \"data\" : {\n" +
" \"message\": \"hellobrother@;;;@http://www.helpme.com/\"\n" +
" }\n" +
"}\n";
// Dump out the HTTP send for debugging
for (String[] hed : MESSAGE_HEADERS) {
System.out.println(hed[0] + "=>" + hed[1]);
}
System.out.println(jsonMessage);
// Actually send it.
sendMessage(POST_URL, MESSAGE_HEADERS, jsonMessage);
}
private static void sendMessage(String postUrl, String[][] messageHeaders,
String jsonMessage) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(postUrl).openConnection();
for (String[] h : messageHeaders) {
conn.setRequestProperty(h[0], h[1]);
}
System.out.println("Connected to " + postUrl);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false); // ensure response always from server
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(conn.getOutputStream()));
pw.print(jsonMessage);
pw.close();
System.out.println("Connection status code " + conn.getResponseCode());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment