HttpsURLConnection 400错误的请求发生错误

时间:2018-11-21 00:27:22

标签: java android ios swift firebase

我需要将下面的Swift代码转换为Java。 Swift代码有效。 但是,Java代码无法正常工作。

HttpsURLConnection失败。

responseCode:400(HttpsURLConnection.getResponseCode())

message2:错误的请求(HttpsURLConnection.getResponseMessage())

如何解决400错误的请求错误。

在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());
        }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

您的JSON请求正文不正确。它产生{"to": zxc},它是无效的json。更改为

String str = "{\"to\": \"" + token + "\", \"notification\": { \"body\": \"" +
    message + "\", \"badge\": \"1\"}}";