Created
November 21, 2014 10:28
-
-
Save Krishan14sharma/289e7f68b498ff8ba603 to your computer and use it in GitHub Desktop.
GCM Mock server code
This file contains 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
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