PieSocket logo

Publish with Java

Use the following code snippet to publish a message on a WebSocket channel with Java.

public class Publish {

  public static void main(String[] args) {

    OkHttpClient client = new OkHttpClient().newBuilder().build();
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(
      //Demo secret and key, get yours at piesocket.com
      "{\n    \"key\": \"oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm\",\n    \"secret\": \"d8129f82f8dd71910aa4a7efa30a7297\",\n    \"channelId\": 1,\n    \"message\": \"Hello world!\"\n}"
    Request request = new Request.Builder()
      .method("POST", body)
      .addHeader("Content-Type", "application/json")
    Response response = client.newCall(request).execute();



This sends a JSON message to channel 1.

Please note that this example uses a demo key and secret, which is public. The demo key is only for quick testing purposes, and you should not use this in your application.

You can get your free API key and API secret here.


Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.