我試圖在Android應用程序中實現Firebase主題消息傳遞,並且試圖構建HTTP發佈請求,並且我收到的響應代碼爲400。我已經看過各種解決方案,但他們似乎都沒有幫助。HTTP發佈請求:錯誤400,Firebase主題消息傳遞
這裏就是我所說的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
請讓我知道,如果有幫我調試需要額外的代碼片段。提前致謝!
請不要在您的Android應用程序中包含此代碼。您正在將您的'AUTH_KEY'暴露給您應用的所有用戶,這意味着它可以(而且將會)被黑客發現,黑客可以用它代表您的應用發送消息。 –
似乎firebase要求我這樣做,但是。有沒有解決方法? – kmindspark
您應該使用應用程序服務器。或者從Firebase控制檯發送通知。將您的服務器密鑰嵌入到客戶端APK中*不是您想要的選擇。 –