从Java服务器向服务器发送推送通知

时间:2016-06-29 02:04:48

标签: java android firebase firebase-cloud-messaging

我正在努力使用新的FCM ...之前我使用过FCM,现在我正在尝试使用FCM ...

我正在尝试将我的应用服务器的推送通知发送到Android设备。

我想使用标准的Java包,尽量不要使用其他如Vert.x,apache的httpClient等...

这是我的代码:

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

我得到的响应代码是401,这意味着未经授权......我猜凭证的格式是错误的......

json字符串是有效的json格式,所以我不想使用JSONObject。

对于字符串凭据,我试过" key:" + apiKey;但仍然得到了相同的结果。

apiKey字符串是从google-services.json中复制的,我是从谷歌的Firebase控制台下载的。

谷歌没有给出一个很好的例子......只是给了我这个:https://firebase.google.com/docs/cloud-messaging/downstream

如果有人知道该怎么做,请回复。谢谢!

4 个答案:

答案 0 :(得分:18)

完整示例使用此功能在JAVA中使用FCM发送通知

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.pushFCMNotification("USER_DEVICE_TOKEN");
    }
}

答案 1 :(得分:2)

你提到你从google-services.json文件获得密钥。这将是您的Android API密钥,而不是发送FCM消息所需的服务器密钥。在Firebase控制台中,转到~jenminervas/code/.git以获取用于发送FCM消息的API密钥。

答案 2 :(得分:0)

据我所知,没有必要对凭证进行base64编码:

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

答案 3 :(得分:0)

这是一个用于从java向app android发送通知的函数。此代码使用JSONObject,您必须将此jar添加到项目构建路径中。

注意:我使用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();
    }
    }
祝你好运

相关问题