gpt4 book ai didi

java - 什么是 Java 等同于使用 https ://fcm. googleapis.com/fcm/send REST Api

转载 作者:搜寻专家 更新时间:2023-10-31 19:53:18 27 4
gpt4 key购买 nike

我已经尝试在 Curl 中使用以下命令使用 Firebase REST Api 发送通知并且它有效:

curl -X POST --header "Authorization: key=AIza...iD9wk" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"to\": \"cAhmJfN...bNau9z\"}"

现在我正尝试在 Java 中做同样的事情,但我找不到一种简单的方法来做同样的事情,而且我尝试过的任何方法都不会触发我的移动端点中的通知。

这是我最接近的方法:

    try {
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Authorization: key", "AIza...iD9wk");
httpcon.setRequestMethod("POST");
httpcon.connect();
System.out.println("Connected!");

byte[] outputBytes = "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"to\": \"cAhmJfN...bNau9z\"}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();

// Reading response
InputStream input = httpcon.getInputStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}

System.out.println("Http POST request sent!");
} catch (IOException e) {
e.printStackTrace();
}

但后来我得到:

java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at httpclient.test.MyHttpClientPost.sendNotification(MyHttpClientPost.java:131)
at httpclient.test.MyHttpClientPost.main(MyHttpClientPost.java:26)

最佳答案

401 表示未经授权,因此未发送有效的 Authorization header 。

还有这一行:

httpcon.setRequestProperty("Authorization: key", "AIza...iD9wk");

不等同于 -H "Authorization: key=AIza...iD9wk"。第一个参数应该是 header 名称,即 Authorization:

httpcon.setRequestProperty("Authorization", "key=AIza...iD9wk");

总之,您误解了 HTTP header 的格式。基本上, header 名称和值由 : 而不是 = 分隔。

关于java - 什么是 Java 等同于使用 https ://fcm. googleapis.com/fcm/send REST Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37978856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com