【问题标题】:Java Server -- send Push with POST to google Firebase CloudJava 服务器——使用 POST 向 Google Firebase Cloud 发送推送
【发布时间】:2016-08-26 06:31:51
【问题描述】:

在我测试推送通知与 Postman 一起使用后,我想在我的应用程序中发送消息时向 FCM 发送推送请求。调用的函数将转到我的 Java 服务器并调用如下函数:

@POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response sendMsg(Message m) throws ExceptionFacade {
...
}

所以每次我调用这个函数时,我都想用一个 json 向https://fcm.googleapis.com/fcm/send 发送一个 POST 请求。

我想知道是否已经为 Java 服务器准备好了代码?以及如何实现它的一些帮助。

我也不明白是否可以使用 php 文件来执行此操作(我发现类似 https://github.com/Paragraph1/php-fcm 的东西)。我正在使用 angularjs。

谢谢你们!

【问题讨论】:

  • 我想我不明白。所以你问如何在java中发送http请求?
  • 是的,我认为它有库?
  • 我的意思是在 Postman 中执行与 java 中相同的 POST 请求
  • 网上有很多可用的资源。例如这个 SO 答案:stackoverflow.com/a/3325065/2633917
  • 导入有些麻烦,导入org.apache.http.HttpEntity;导入 org.apache.http.HttpResponse;导入 org.apache.http.client.HttpClient;导入 org.apache.http.client.methods.HttpPost;导入 org.apache.http.entity.StringEntity;

标签: java angularjs firebase http-post firebase-cloud-messaging


【解决方案1】:

这是运行良好的最终代码! 它正在发送这样的json:

{
 "to" : "...",
 "priority" : "high",
 "notification" : {
                   "title" : "hello",
                   "body" : "me"
  }
}

//不要忘记添加common-codec和common-login jar来构建成功。

public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws JSONException, IOException {

                HttpClient client = HttpClientBuilder.create().build();
                HttpPost post = new HttpPost("https://fcm.googleapis.com/fcm/send");
                post.setHeader("Content-type", "application/json");
                post.setHeader("Authorization", "key=FCM-API-KEY");
                JSONObject message = new JSONObject();
                message.put("to", "TOKEN-FCM-OF-THE-DEVICE");
                message.put("priority", "high");
                JSONObject notification = new JSONObject();
                notification.put("title", "Me");
                notification.put("body", "New message");
                message.put("notification", notification);
                post.setEntity(new StringEntity(message.toString(), "UTF-8"));
                HttpResponse response = client.execute(post);

                System.out.println(response);
                System.out.println(message);
    }

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 2020-09-14
    • 2018-02-22
    • 2023-03-30
    • 2019-02-10
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多