【发布时间】:2017-01-10 02:41:03
【问题描述】:
我正在尝试在 Android 应用程序中实现 Firebase 主题消息传递,并且我正在尝试构建一个 HTTP 发布请求,我收到的响应代码为 400。我查看了各种解决方案,但没有一个似乎有所帮助。
这里是我调用 AsyncTask 子类的地方:
try{new FirebaseSendMessage().execute("Hello world");}
catch (Exception e) {
Log.d("Exception", e.toString());
}
这是我的异步任务类的子类。
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());
}
}
}
错误:I/System.out: POST Response Code :: 400
如果需要额外的代码 sn-ps 来帮助我调试,请告诉我。提前致谢!
【问题讨论】:
-
请不要在您的 Android 应用程序中包含此代码。您将
AUTH_KEY暴露给您应用的所有用户,这意味着它可以(并且将会)被黑客找到,然后黑客可以使用它代表您的应用发送消息。 -
看来firebase要求我这样做。有解决办法吗?
-
您应该使用应用服务器。或者从 Firebase 控制台发送通知。在客户端 APK 中嵌入服务器密钥不是您应该想要的替代方法。
标签: android http firebase http-post firebase-cloud-messaging