如何通过java服务器使用FCM向Android设备发送推送通知?

如何通过java服务器使用FCM向Android设备发送推送通知?

问题描述:

我用Java服务器代码编写了使用fcm发送通知的代码。但是它是抛出异常服务器返回的HTTP响应代码:500的URL: https://fcm.googleapis .com / fcm / send

I have write this code for send notification using fcm by java server code. But it is throwing exception Server returned HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send

public static void pushFCMNotification(String userDeviceIdKey) throws     Exception{

    String authKey = AUTH_KEY_FCM;   // You FCM AUTH key
    String FMCurl = API_URL_FCM;     

    URL url = new URL(FMCurl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization","key="+authKey);
    conn.setRequestProperty("Content-Type","application/json");

    JSONObject json = new JSONObject();
    json.put("to",userDeviceIdKey.trim());
    JSONObject info = new JSONObject();
    info.put("title", "Notificatoin Title");   // Notification title
    info.put("body", "Hello Test notification"); // Notification body
    json.put("notification", info);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(json.toString());
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + json);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();


    /*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(json.toString());
    wr.flush();
    conn.getInputStream();*/
    }


根据说明文件:


500-599范围内的错误(如500或503)表示在尝试处理请求或服务器暂时不可用时,FCM连接服务器出现内部错误(例如,由于超时)。发送方必须稍后重试,以履行响应中包含的任何Retry-After标头。应用服务器必须执行指数退避。

Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.

源: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

但是,请确保JSON请求格式正确。尝试使用 json.toString()更新您的问题,并使用以下描述的过程检查您的API密钥是否仍然有效:检查服务器密钥的有效性

However, make sure that the JSON request is properly formatted. Try to update your question with the json.toString() and check that your API key is still valid using the procedure described in: Checking the validity of a server key