kmi*_*ark 2 android http http-post firebase firebase-cloud-messaging
我正在尝试在Android应用程序中实现Firebase主题消息,我正在尝试构建一个HTTP post请求,并且我收到的响应代码为400.我已经查看了各种解决方案,但它们似乎都没有救命.
这是我调用AsyncTask的子类的地方:
try{new FirebaseSendMessage().execute("Hello world");}
catch (Exception e) {
Log.d("Exception", e.toString());
}
Run Code Online (Sandbox Code Playgroud)
这是我的Async Task类的子类.
class FirebaseSendMessage extends AsyncTask<String, Integer, Double> {
private final static String USER_AGENT = "Mozilla/5.0";
private final static String AUTH_KEY = "<My firebase authorization key obtained from firebase>";
private Exception exception;
protected Double doInBackground(String... params) {
try {
sendRequest(params);
} catch (Exception e) {
this.exception = e;
}
return null;
}
protected void onPostExecute(Long l) {
// TODO: check this.exception
// TODO: do something with the feed
}
public void sendRequest(String... params) {
try {
String urlString = "https://fcm.googleapis.com/fcm/send";
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "key=" + AUTH_KEY);
String postJsonData = "{\"to\": \"/topics/news\"\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\"}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postJsonData);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK){
System.out.println("succeeded");
}
/*InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//con.disconnect();*/
}
catch(IOException e){
Log.d("exception thrown: ", e.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
}
错误: I/System.out: POST Response Code :: 400
如果有其他代码片段可以帮助我调试,请告诉我.提前致谢!
错误400表示请求中的无效JSON:
检查JSON消息是否格式正确并包含有效字段(例如,确保传入正确的数据类型).
在你的sendRequest,你错过了一个逗号(,之间)"news\",并\"data\"和右括号(}):
String postJsonData = "{\"to\": \"/topics/news\"\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\"}";
Run Code Online (Sandbox Code Playgroud)
看起来像这样:
{"to": "/topics/news/""data":{"message":"...."}
Run Code Online (Sandbox Code Playgroud)
应该:
String postJsonData = "{\"to\": \"/topics/news\", \"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\"}}";
Run Code Online (Sandbox Code Playgroud)
这样JSON结构就是正确的:
{"to": "/topics/news/",
"data":{"message":"..."}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10792 次 |
| 最近记录: |