我正在尝试在服务器中请求 Google Firebase 的 POST。我按照文档指南进行操作,但没有成功。
我的发送消息功能如下。
private static void sendMsg() throws IOException
{
String url = "https://fcm.googleapis.com/fcm/send";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "key=XXXX");
JSONObject msg=new JSONObject();
msg.put("message","test8");
JSONObject parent=new JSONObject();
parent.put("to", "XXXXX");
parent.put("data", msg);
con.setDoOutput(true);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + parent.toString());
System.out.println("Response Code : " + responseCode+" "+con.getResponseMessage());
}
响应代码是“411”,消息是“长度要求”。 我也尝试过设置内容长度,但结果是一样的。
我做错了吗?
最佳答案
您的所有设置均正确,但尚未写入数据。添加所示的语句:
con.setDoOutput(true);
// Added
OutputStreamWriter os = new OutputStreamWriter(con.getOutputStream());
os.write(parent.toString());
os.flush();
os.close();
关于java - Google Firebase HTTP 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44836435/