1

Now I am trying to implement Firebase Cloud Messaging in my Java program. To send push-notifications through FCM. Now, FCM tells me to send it like an HTTP POST request.

This is the request I am trying to send:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{  "data": {
     "score": "5x1",
     "time": "15:10"
   },
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

How do I send this from my Eclipse Java program?

AL.
  • 36,815
  • 10
  • 142
  • 281
Peter
  • 1,848
  • 4
  • 26
  • 44

2 Answers2

3

It is very easy with httpclient, here is example

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class HttpClientUtils {

    public JSONObject doPost() {
        HttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost("https://fcm.googleapis.com/fcm/send");
        JSONObject result = new JSONObject();
        try {
            String bodyContent = "{  'data': {    'score': '5x1',     'time': '15:10'   },   'to' : 'bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...'}";
            StringEntity requestBody = new StringEntity(bodyContent);
            request.setEntity(requestBody);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Authorization", "key=AIzaSyZ-1u...0GBYzPu7Udno5aA");
            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity);
            result.put("status", response.getStatusLine().getStatusCode());
            result.put("bodyContent", new JSONObject(responseString));
        } catch (ClientProtocolException e) {
            result.put("status", "500");
            result.put("bodyContent", "");
            e.printStackTrace();
        } catch (IOException e) {
            result.put("status", "500");
            result.put("bodyContent", "");
            e.printStackTrace();
        } finally {
            request.releaseConnection();
        }
        return result;
    }


}
Manh Trinh
  • 56
  • 4
  • Okay two problems here. 1) I get this error message when importing `The import of org.apache.http.impl.client.HttpClientBuilder cannot be resolved`. 2) When trying to `request.releaseConnection()`I get this error message `The method releaseConnection() is undefined for the type HttpPost`.. – Peter Oct 12 '16 at 08:22
  • For missing lib, using this dependency
    https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.2
    – Manh Trinh Oct 17 '16 at 03:56
0

Create FCM request class -

@JsonInclude(JsonInclude.Include.NON_NULL)
    public static class FCMRequest {
        @JsonProperty("type")
        private String type;
        @JsonProperty("expiry")
        private String expiry;
        @JsonProperty("body")
        private String body;
        @JsonProperty("title")
        private String title;
        @JsonProperty("subscriberId")
        private String subscriberId;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getExpiry() {
            return expiry;
        }

        public void setExpiry(String expiry) {
            this.expiry = expiry;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getSubscriberId() {
            return subscriberId;
        }

        public void setSubscriberId(String subscriberId) {
            this.subscriberId = subscriberId;
        }
    }

Create FCM request payload and for sending POST request to FCM, you can use Jersey Rest (JAX-RS) Library like below -

FCMRequest fcmRequest = new FCMRequest();
//set the rquest data
    WebTarget target = client.target("https://fcm.googleapis.com/fcm/send");
                Entity<FCMRequest> entity = Entity.entity(fcmRequest, MediaType.APPLICATION_JSON_TYPE);
                Response authResponse = target.request()
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                        .header(HttpHeaders.AUTHORIZATION, KEY)
                        .post(entity, Response.class);
Derrick
  • 3,669
  • 5
  • 35
  • 50
  • When I create a new class and add your content I get errors on all the `JsonInclude` and `JsonPropertys` (`JsonInclude cannot be resolved to a type` and `JsonProperty cannot be resolved to a type`). – Peter Oct 12 '16 at 08:25
  • Just make sure you have imported the following classes before the class initialization - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; – Derrick Oct 12 '16 at 09:28