2016-06-29 29 views
9

Sto lottando con il nuovo FCM ... ho usato FCM prima, ora sto cercando di FCM ...Invia notifica push da server a dispositivo Android in Java

Sto cercando di inviare notifiche push per la mia app server per dispositivo Android.

Voglio usare il pacchetto standard di Java, cercate di non usare altri, come Vert.x, apache di HttpClient ecc ...

Ecco il mio codice:

public void sendNotification(String messageBody) 
{ 
    try 
    { 
     URL url = new URL("https://fcm.googleapis.com/fcm/send"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setDoInput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json"); 

     String apiKey = "AI...wE"; 

     String credentials = "key=" + apiKey; 
     //String basicAuth = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes()); 

     String basicAuth = "Basic " + new String(Base64.encodeBase64(credentials.getBytes())); 

     conn.setRequestProperty ("Authorization", basicAuth); 

     String notfnStr = "{\"body\": \"this is my body\", \"title\": \"this is my title\"}"; 
     String dataStr = "{\"key1\": \"value1\", \"key2\": \"value2\"}"; 

     String bodyStr = "{\"priority\": \"high\", \"to\": \"dFC8GW0N1Q8:APA91bHePPmC7QVV16LGnR6rqxwreHSv1GgawijZ_dZL9T70ZkiXIV8TW_ymAWkvFfXRiWJmtR_UGBXBv2iV2UhS8M-Tndw8sf8ZW6zIqfaiiVJao3G5HFbhqgA18ukNNtW_J7JaWkz8\", " + 
       "\"notification\": " + notfnStr + ", \"data\": " + dataStr + "}"; 

     System.out.println("### input: " + bodyStr); 

     OutputStream os = conn.getOutputStream(); 
     os.write(bodyStr.getBytes()); 
     os.flush(); 

     if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { 
      throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); 
     } 

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

     conn.disconnect(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

il codice di risposta ho ottenuto è 401, il che significa non autorizzato ... Immagino che il formato delle credenziali sia sbagliato ...

La stringa json è in formato JSON valido, quindi non mi prendo la briga di usare JSONObject.

Per le credenziali di stringa, ho provato "chiave:" + apiKey; ma ha ancora lo stesso risultato.

La stringa apiKey viene copiata da google-services.json che ho scaricato dalla console Firebase in google.

Google non ha dato un buon esempio ... solo mi ha dato questo: https://firebase.google.com/docs/cloud-messaging/downstream

Se qualcuno sa come farlo, si prega di rispondere. Grazie!!

risposta

0

Per quanto ne so non v'è alcuna necessità di base64 codificare le credenziali:

String apiKey = "AI...wE"; 
String credentials = "key=" + apiKey; 
conn.setRequestProperty ("Authorization", credentials); 
+0

No, ho provato, ho ancora ricevuto il codice di risposta 401 ... – fkie4

1

Lei ha detto che avete ottenuto lui chiave dal file di google-services.json. Questa sarebbe la tua chiave API Android, non la chiave del server richiesta per inviare messaggi FCM. Nella console Firebase andare a Settings > Cloud Messaging > Server key per la chiave API da utilizzare per l'invio di messaggi FCM.

+0

Ciao. Solo una rapida domanda, signore Thompson. @ fkie4 ha anche detto di aver scaricato il file 'google-services.json' dalla Firebase Console. La Firebase Console non fornisce automaticamente la chiave server corrispondente in "google-services.json"? –

+0

Ha! sta funzionando ora. Grazie! Stavo usando una chiave API sbagliata ... inoltre, non viene utilizzata la codifica Base64. io uso conn.setRequestProperty ("Autorizzazione", "chiave =" + apiKey); Grazie @frank !! – fkie4

+1

Np. @intj Nessuna chiave del server dovrebbe mai essere realmente inclusa o utilizzata dall'applicazione client. –

13

PIENA ESEMPIO usare questo per inviare la notifica UTILIZZO FCM IN JAVA

public class FCMNotification { 

    // Method to send Notifications from server to client end. 
    public final static String AUTH_KEY_FCM = "API_KEY_HERE"; 
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; 

    public static void pushFCMNotification(String DeviceIdKey) 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 data = new JSONObject(); 
     data.put("to", DeviceIdKey.trim()); 
     JSONObject info = new JSONObject(); 
     info.put("title", "FCM Notificatoin Title"); // Notification title 
     info.put("body", "Hello First Test notification"); // Notification body 
     data.put("data", info); 

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

     int responseCode = conn.getResponseCode(); 
     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(); 

    } 

    @SuppressWarnings("static-access") 
    public static void main(String[] args) throws Exception { 
     FCMNotification obj = new FCMNotification(); 
     obj.pushFCMNotification(
       "USER_DEVICE_TOKEN"); 
    } 
} 
+0

Questo è sorprendente. – grant

+0

bravi uomini di lavoro. ma voglio mandare più di un token? – marlonpya

+1

trova che .. cambia ** in ** per ** registration_ids ** aggiungi 'JSONArray' – marlonpya

0

Questa è una funzione che utilizza per inviare la notifica da Java a Android app. questo codice usa JSONObject per aggiungere questo jar al percorso di costruzione del progetto.

nota: Io uso FCM

import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import org.json.JSONObject; 

public class FcmNotif { 
public final static String AUTH_KEY_FCM ="AIzB***********RFA"; 

public final static String API_URL_FCM ="https://fcm.googleapis.com/fcm/send"; 

     // userDeviceIdKey is the device id you will query from your database 

    public void pushFCMNotification(String userDeviceIdKey, String title, String message) 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", title); // Notification title 
    info.put("body", message); // Notification body 
    info.put("image", "https://lh6.googleusercontent.com/-sYITU_cFMVg/AAAAAAAAAAI/AAAAAAAAABM/JmQNdKRPSBg/photo.jpg"); 
    info.put("type", "message"); 
    json.put("data", info); 
    System.out.println(json.toString()); 

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

buona fortuna