Java Android FCM向用户Server发送消息返回HTTP响应代码

时间:2017-03-29 12:16:27

标签: java android firebase firebase-cloud-messaging

我这样做了:

public class PushNotifictionHelper {
    public final static String AUTH_KEY_FCM = "AIzaSyD63pfTvnwhe9WVuIe.........";
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    public static String sendPushNotification(String deviceToken)
            throws IOException, JSONException {
        String result = "";
        URL url = new URL(API_URL_FCM);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

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

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

        JSONObject json = new JSONObject();

        json.put("to", deviceToken.trim());
        JSONObject info = new JSONObject();
        info.put("title", "notification title"); // Notification title
        info.put("body", "message body"); // Notification
        // body
        json.put("notification", info);
        try {
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            result = "OK";
        } catch (Exception e) {
            e.printStackTrace();
            result = "BAD";
        }
        System.out.println("GCM Notification is sent successfully");

        return result;

    }

    public static void main(String [] args){
        try {
            PushNotifictionHelper.sendPushNotification("ep51x3Ckmig:APA91bG4PdoJC7zGlV0JPmCA49jmqJCkeSPH1QzF9byxdH1nRlFOVyAi9ppO2ygoSpp8s44o1oGO8n-HCJDB_oZAZ6WCwFD2a9yAFmKIpKhmPXakeLf-ktqPnzwf-GFziv7_nMdVPIci");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

当我在控制台中运行时,我看到了

java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send

我从网上得到的AUTH_KEY_FCM:

Klucz interfejsu Web API AIzaSyD63pfTvnwhe9WVuIe.........

1 个答案:

答案 0 :(得分:3)

401错误是指身份验证错误。来自docs

  

用于发送邮件的发件人帐户无法通过身份验证。可能的原因是:

     
      
  • 缺少授权标头或HTTP请求中的语法无效。
  •   
  • 作为密钥发送的项目编号无效。
  •   
  • 密钥有效,但已禁用FCM服务。
  •   
  • 请求来自服务器密钥IP中未列入白名单的服务器。
  •   
     

检查您在Authentication标头内发送的令牌是否是与您的项目关联的正确服务器密钥。有关详细信息,请参阅Checking the validity of a Server key

使用FCM时,您应始终使用 Cloud Messaging 标签中的 服务器密钥 (而不是Web API密钥)在Firebase Console