Create simple Java application to post JSON message to CometD Bayeux Channel using Apache HttpClient and Maven style NetBeans project

The objective discussed in this article is to post messages to a CometD Bayeux Channel with a standalone Java Class – without dependencies on CometD. For example to control from Java the Slideshow introduced in the synchronized Slideshow demo application created using CometD (see previous articles Push based synchronized Slideshow demo application implemented using CometD and jQuery running on Tomcat and Publishing to CometD Bayeux Channel from inside the Oracle Database – PL/SQL based push to CometD Web Client ).

This article describes the creation of a simple Java Class leveraging Apache HttpClient to post HTTP requests (JSON messages) to a CometD Bayeux Channel. The main point is to show working code with the lest dependencies, not an optimal program (it is far from optimal). The article demonstrates how NetBeans and Maven conspire here to make the task as simple as possible. The Maven support in NetBeans allows me to simply create a new Maven style project of (arche)type Java Application.

I can then add the dependency entry for Apache HttpClient to the pom.xml. When I next Build the NetBeans project With Dependencies, the required JAR-files are downloaded to my local Maven Repository (see this article for getting going with Maven:NetBeans 7.1 – JavaFX 2.0 support, refactoring enhancements and great Maven 3 integration and Preparing your environment for modern open source Java libraries and frameworks using Git and Maven, throwing in Tomcat as a bonus ).

Using the example code from the article mentioned below in the Resources, it is a breeze to make a POST request with JSON payload. After figuring out the JSON messages required by CometD – one for handshaking and one for publishing the slide selection message – as is described in Publishing to CometD Bayeux Channel from inside the Oracle Database – PL/SQL based push to CometD Web Client ), it is just a short step to control the slideshow from Java with two simple JSON messages.



1. Create NetBeans project of type Maven – Java Application


Then select Maven, Java Application and press Next:


Set the properties for the project and click on Finish:


2. Add dependency for Apache HttpClient

The Maven pom.xml file is created based on the these properties. The dependency on Apache HttpClient can be added in the dependencies element:


3. Create Java Class that can make Http Post request with JSON content

The class JavaCometPublisher is created. It contains method postToURL() that is the bare minimum piece of code required to make a HTTP Post request and pass some JSON content:

package nl.amis.comet.client.javapublisher;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class JavaCometPublisher {

    private static String postToURL(String url, String message, DefaultHttpClient httpClient) throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException {
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(message);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());

        BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));

        String output;
        StringBuffer totalOutput = new StringBuffer();
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
        return totalOutput.toString();

4. Use Http Post to handshake with CometD and publish to Bayeux Channel

With this postJsonToUrl() method at our disposal, it becomes easy to connect to CometD and publish to the /slide/show channel. This is done in method setSlide():

    public static void setSlide(int slideNumber) throws IOException {
        String url = "http://localhost:8085/slideshow/cometd";
        String message = "[{\"version\":\"1.0\",\"minimumVersion\":\"0.9\",\"channel\":\"/meta/handshake\",\"supportedConnectionTypes\":[\"long-polling\",\"callback-polling\"],\"advice\":{\"timeout\":60000,\"interval\":0},\"id\":\"1\"}]";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String response = postToURL(url, message, httpClient);
        String clientId = response.substring(155, response.indexOf("\"", 155));
        String slideSelectionMessage = "[{\"channel\":\"/slide/show\",\"data\":{\"uniqueId\":1326523938212,\"slideNumber\":" + slideNumber + "},\"id\":\"40\",\"clientId\":\"" + clientId + "\"}]";
        response = postToURL(url, slideSelectionMessage, httpClient);

6. Create the main method that runs the slideshow:

    public static void main(String[] args) throws InterruptedException {
        JavaCometPublisher p = new JavaCometPublisher();
        try {
        } catch (MalformedURLException e) {
        } catch (IOException e) {

7. Run the Java Class and take control of that slideshow


Download NetBeans project described in this article:

Article describing the creation of an HTTP POST client using Apache HttpClient: