Java Backend Sample


Send push notifications to your users with this Java code sample.

Warning: This sample code is for Java server-side use only. Do NOT send push notifications directly from your Android application, otherwise, your Secret API Key will be compromised.

The following code will send a push notification to devices with {message: "Hello World!"} as the payload.

public static void sendSamplePush() {
	// Prepare list of target device tokens
	List<String> deviceTokens = new ArrayList<>();

	// Add your device tokens here
    deviceTokens.add("cdd92f4ce847efa5c7f");
    
	// Convert to String[] array
	String[] to = deviceTokens.toArray(new String[deviceTokens.size()]);

	// Optionally, send to a publish/subscribe topic instead
	// String to = '/topics/news';

	// Set payload (any object, it will be serialized to JSON)
	Map<String, String> payload = new HashMap<>();

	// Add "message" parameter to payload
	payload.put("message", "Hello World!");

	// iOS notification fields
	Map<String, Object> notification = new HashMap<>();

	notification.put("badge", 1);
	notification.put("sound", "ping.aiff");
	notification.put("title", "Test Notification");
	notification.put("body", "Hello World \u270c");

	// Prepare the push request
	PushyAPI.PushyPushRequest push = new PushyAPI.PushyPushRequest(payload, to, notification);

	try {
		// Try sending the push notification
		PushyAPI.sendPush(push);
	}
	catch (Exception exc) {
		// Error, print to console
		System.out.println(exc.toString());
	}
}

Create a file named PushyAPI.java and paste the following code inside it:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.ByteArrayEntity;

import java.util.Map;

public class PushyAPI {
    public static ObjectMapper mapper = new ObjectMapper();
    
    // Insert your Secret API Key here
    public static final String SECRET_API_KEY = "SECRET_API_KEY";

    public static void sendPush(PushyPushRequest req) throws Exception {
        // Get custom HTTP client
        HttpClient client = new DefaultHttpClient();

        // Create POST request
        HttpPost request = new HttpPost("https://api.pushy.me/push?api_key=" + SECRET_API_KEY);

        // Set content type to JSON
        request.addHeader("Content-Type", "application/json");

        // Convert post data to JSON
        byte[] json = mapper.writeValueAsBytes(req);

        // Send post data as byte array
        request.setEntity(new ByteArrayEntity(json));

        // Execute the request
        HttpResponse response = client.execute(request, new BasicHttpContext());

        // Get response JSON as string
        String responseJSON = EntityUtils.toString(response.getEntity());

        // Convert JSON response into HashMap
        Map<String, Object> map = mapper.readValue(responseJSON, Map.class);

        // Got an error?
        if (map.containsKey("error")) {
            // Throw it
            throw new Exception(map.get("error").toString());
        }
    }

    public static class PushyPushRequest {
        public Object to;
        public Object data;

        public Object notification;

        public PushyPushRequest(Object data, Object to, Object notification) {
            this.to = to;
            this.data = data;
            this.notification = notification;
        }
    }
}

Note: Make sure to replace SECRET_API_KEY with your app's Secret API Key, available in the Pushy Dashboard (Click your app -> API Authentication tab). This is a backend API endpoint. Never expose your application's Secret API Key in your client code.