Cam*_*gón 6 java post curl http firebase
我已经在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\"}"
Run Code Online (Sandbox Code Playgroud)
既然我正在尝试在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();
}
Run Code Online (Sandbox Code Playgroud)
但后来我得到:
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)
Run Code Online (Sandbox Code Playgroud)
401表示未经授权,因此未Authorization发送有效标头.
这一行:
httpcon.setRequestProperty("Authorization: key", "AIza...iD9wk");
Run Code Online (Sandbox Code Playgroud)
不等于-H "Authorization: key=AIza...iD9wk".第一个参数应该是标题名称,即Authorization:
httpcon.setRequestProperty("Authorization", "key=AIza...iD9wk");
Run Code Online (Sandbox Code Playgroud)
总之,您误解了HTTP标头的格式.基本上标题名称和值由:not 分隔=.