Мне нужно преобразовать приведенный ниже код Swift в Java.Свифт код работает.Но код Java не работает.
Сбой HttpsURLConnection.
responseCode: 400 (HttpsURLConnection.getResponseCode ())
message2: Неверный запрос (HttpsURLConnection.getResponseMessage ())
Как я могу исправить ошибку 400 Bad Request.
В Swift (это работало)
func sendNotification(token: String, message: String) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(firebaseServerKey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
request.httpBody = "{\"to\":\"\(token)\",\"notification\":{\"body\":\"\(message)\",\"badge\":\"1\"}}".data(using: .utf8)
}
Я написал в JAVA (не работал)
private void sendNotification(String token, String message) {
//Firebase CloudMessaging serverkey
var firebaseServerKey = "AAAAA6qLps4:APA91bE7szGAgp3qYGOJsrSsrM1InhIgf5Fq1xxxxxx"
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+firebaseServerKey);
String str = "{\"to\": " + token + ", \"notification\": { \"body\": " + message + ", \"badge\": \"1\"}}";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.close();
int responseCode = conn.getResponseCode(); // responseCode: 400
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.d("Success", String.valueOf(responseCode));
} else {
String code = String.valueOf(responseCode);
String message2 = conn.getResponseMessage(); // message2: Bad Request
Log.d("Fail", String.valueOf(responseCode));
Log.d("Fail2", conn.getResponseMessage());
}
}