fcm算法 java_使用Java(而非FCM控制台)发送Firebase通知

在尝试使用Java代码而非Firebase控制台向Android应用发送FCM通知时遇到问题。虽然HTTP响应代码为200,但通知并未显示。代码中包含了建立连接、设置请求头、构造JSON对象以及处理响应的过程。在输出中只看到'Response Code: 200',但通知没有成功发送。
摘要由CSDN通过智能技术生成

我正在向Android应用程序添加通知,但似乎无法通过Java代码发送通知.我从响应中获取了200 http代码,但未显示任何内容.

这可以在Firebase控制台本身上运行,但是一旦尝试使用Java代码,事情就会发生.

这是我的下面的代码

package actions.authentication;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.URL;

import com.opensymphony.xwork2.Action;

import edocs.actions.PublicAction;

import net.sf.json.JSONObject;

public class SendPushNotification extends PublicAction {

/**

*

*/

private static final long serialVersionUID = -8022560668279505764L;

// Method to send Notifications from server to client end.

public final static String AUTH_KEY_FCM = "SERVER_KEY_HERE";

public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

public final static String DEVICE_ID = "DEVICE_TOKEN_HERE";

public String execute() {

String DeviceIdKey = DEVICE_ID;

String authKey = AUTH_KEY_FCM;

String FMCurl = API_URL_FCM;

try {

URL url = new URL(FMCurl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setUseCaches(false);

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("Authorization", "key=" + authKey);

conn.setRequestProperty("Content-Type", "application/json");

System.out.println(DeviceIdKey);

JSONObject data = new JSONObject();

data.put("to", DeviceIdKey.trim());

JSONObject info = new JSONObject();

info.put("title", "FCM Notificatoin Title"); // Notification title

info.put("body", "Hello First Test notification"); // Notification body

data.put("data", info);

System.out.println(data.toString());

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

wr.write(data.toString());

wr.flush();

wr.close();

int responseCode = conn.getResponseCode();

System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

in.close();

return Action.SUCCESS;

}

catch(Exception e)

{

System.out.println(e);

}

return Action.SUCCESS;

}

}

行System.out.println(“ Response Code:” responseCode);打印出以下内容

Response Code : 200

有没有其他人有这个问题?任何帮助将不胜感激

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值