6
private void sendMsg() { 
    DBManager dbManager = DBManager.getInstance(); 
    ArrayList<String> firebaseIds; 

    try { 
     ResultSet rs= dbManager.getRegisteredFirebaseDevice(); 
     while(rs.next()){ 
      System.out.println(rs.getString(1)); 
      firebaseIds.add(rs.getString(1)); 
     } 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } 

    String url = "https://fcm.googleapis.com/fcm/send"; 
    URL obj = new URL(url); 
    HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

    // add reuqest header 
    con.setRequestMethod("POST"); 
    con.setRequestProperty("Authorization: key", "AIzaSyAl6S936qt_NKKFwwbd-NEmiSGIL7G_yJc"); 
    con.setRequestProperty("Content-Type", "application/json"); 
    // String msg="New design added in "+getCategory(designCategory)+". Design no."+designNo; 
    // String urlParameters = "data.msg="+msg+"&registration_id="+firebaseIds.get(0); 

    JSONObject msg=new JSONObject(); 
    msg.put("msg","New design added in "+getCategory(designCategory)+". Design no."+designNo); 


    JSONObject parent=new JSONObject(); 

    parent.put("to", firebaseIds.get(0)); 
    parent.put("data", msg); 

    // String urlParameters = "registration_id="+firebaseIds.get(0); 
    // Send post request 
    con.setDoOutput(true); 


    OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream()); 
    wr.write(parent.toString()); 

    // DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    // wr.writeBytes(urlParameters); 
    // wr.flush(); 
    // wr.close(); 

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

} 

上記のコードを呼び出すと、401 Unauthorizedという応答が返ってきます。なぜこのエラーが出るのか理解できません。私は適切なサーバーキーを使用しています。私の使っている戦略に構文エラーや何か間違いがありますか?firebase(fcm)が401権限を持たないと言っています

con.setRequestProperty("Authorization: key", "<YOUR API KEY>"); 

で:

con.setRequestProperty("Authorization", "key=<YOUR API KEY>"); 

答えて

8

を踏襲していますクラウドの[メッセージング]タブの[FCMコンソール]にあります。プロジェクト概要では、[管理]に[クラウドメッセージング]タブがあり、SERVER APIキーの使用状況が表示されます。 jsonファイルのclient_apiキーとSERVER_API_KEYは異なる!!

+1

ありがとうございました。 –

+1

今すぐ、thanx –

-1

https://firebase.google.com/docs/cloud-messaging/server

「のAndroid、iOSの。これは、その値Firebaseコンソール設定ペインのクラウドメッセージング]タブで利用可能なサーバキー、であることを確認し、ブラウザキーはFCMによって拒否されています。」

3

Harcoの答えによると、Firebaseコンソールでは、「プロジェクト設定」(歯車のアイコンをクリック)を見て、「クラウドメッセージング」タブを選択します。 「サーバーキー」は必要なものです。 2017年6月28日に実際

enter image description here

関連する問題