Java 发生HttpsURLConnection 400错误请求错误
我需要将下面的Swift代码转换为Java。 Swift代码有效。 但是,Java代码不起作用 HttpsURLConnection已失败 响应代码:400(HttpsURLConnection.getResponseCode()) 消息2:错误的请求(HttpsURLConnection.getResponseMessage()) 如何解决400错误请求错误 在斯威夫特(它起作用了) 我用JAVA写的(没有工作)Java 发生HttpsURLConnection 400错误请求错误,java,android,ios,swift,firebase,Java,Android,Ios,Swift,Firebase,我需要将下面的Swift代码转换为Java。 Swift代码有效。 但是,Java代码不起作用 HttpsURLConnection已失败 响应代码:400(HttpsURLConnection.getResponseCode()) 消息2:错误的请求(HttpsURLConnection.getResponseMessage()) 如何解决400错误请求错误 在斯威夫特(它起作用了) 我用JAVA写的(没有工作) 您的JSON请求正文不正确。它产生{“to”:zxc},这是一个无效的json。
您的JSON请求正文不正确。它产生
{“to”:zxc}
,这是一个无效的json。换成
String str = "{\"to\": \"" + token + "\", \"notification\": { \"body\": \"" +
message + "\", \"badge\": \"1\"}}";
嗨,谢谢。我无法用你的代码建立成功。我对Json不熟悉。我应该如何更改它?嗨,我仍然失败,如下图所示。在那里我更新了它。我签入了我的IDE。又放错地方了对不起
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());
}
}
String str = "{\"to\": \"" + token + "\", \"notification\": { \"body\": \"" +
message + "\", \"badge\": \"1\"}}";