Send HTTP POST Request from Java Application to Google Messaging Service

java-post-gcmTo send notification messages to Android devices you need first to send a POST request from your application to Google Cloud Messaging (GCM) service instructing it to send the notifications. Here we will see how to send POST request to GCM from Java “desktop” application.

Objective:

  • How to successfully send a POST request to Google Cloud Messaging service from Java application?

Environment & Tools:

  • Eclipse
  • Maven (optional)

Library:

  • jackson (2.2.2)

( 1 ) Create Server API Key from Google Developer Console

refer to Creating Server API Key to Send Message From Our Server to Google Cloud Messaging Service

( 2 ) Create a new Java Project

  • com/hmkcode/vo/Contnet.java

This is a simple POJO to hold message content. Message content should contain “registration_ids” of registered applications receiving the notification message. In this article we will assume we have one registration id. read more Request Format

Registration ID: An Android application needs to register with GCM servers before it can receive messages. When an app registers, it receives a registration ID, which it can then store for future use. In this article we are not showing how to get the registration id but we will assume we have one.

package com.hmkcode.vo;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Content implements Serializable {

    private List<String> registration_ids;
    private Map<String,String> data;

    public void addRegId(String regId){
        if(registration_ids == null)
            registration_ids = new LinkedList<String>();
        registration_ids.add(regId);
    }

    public void createData(String title, String message){
        if(data == null)
            data = new HashMap<String,String>();

        data.put("title", title);
        data.put("message", message);
    }
  • com/hmkcode/POST2GCM.java

This is our main class which will send the POST request. Here we need to pass the following:

  1. Server API Key which we created in step 1. This key will be added to POST headers.
  2. Content object which will be converted in JSON format using Jackson library
package com.hmkcode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Content;

public class POST2GCM {

	public static void post(String apiKey, Content content){

		try{

		// 1. URL
		URL url = new URL("https://android.googleapis.com/gcm/send");

		// 2. Open connection
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		// 3. Specify POST method
		conn.setRequestMethod("POST");

		// 4. Set the headers
		conn.setRequestProperty("Content-Type", "application/json");
		conn.setRequestProperty("Authorization", "key="+apiKey);

		conn.setDoOutput(true);

			// 5. Add JSON data into POST request body 

			//`5.1 Use Jackson object mapper to convert Contnet object into JSON
	    	ObjectMapper mapper = new ObjectMapper();

	    	// 5.2 Get connection output stream
			DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

			// 5.3 Copy Content "JSON" into 
			mapper.writeValue(wr, content);

			// 5.4 Send the request
			wr.flush();

			// 5.5 close
			wr.close();

			// 6. Get the response
			int responseCode = conn.getResponseCode();
			System.out.println("\nSending 'POST' request to URL : " + url);
			System.out.println("Response Code : " + responseCode);

			BufferedReader in = new BufferedReader(
			        new InputStreamReader(conn.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			// 7. Print result
			System.out.println(response.toString());

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
}
  • com/hmkcode/App.java
package com.hmkcode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Content;

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Sending POST to GCM" );

        String apiKey = "AIzaSyB8azikXJKi_NjpWcVNJVO0d........";
        Content content = createContent();

        POST2GCM.post(apiKey, content);
    }

    public static Content createContent(){

        Content c = new Content();

        c.addRegId("APA91bFqnQzp0z5IpXWdth1lagGQZw1PTbdBAD13c-UQ0T76BBYVsFrY96MA4SFduBW9RzDguLaad-7l4QWluQcP6zSoX1HSUaAzQYSmI93....");
        c.createData("Test Title", "Test Message");

        return c;
    }
}

( 3 ) Run the Application

After running the application you will receive a response showing if the request is succeeded or not.

Source Code @ GitHub