在Java中将推送通知从服务器发送到Android设备 [英] Send push notification from server to android device in Java

查看:250
本文介绍了在Java中将推送通知从服务器发送到Android设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我试图发送推送通知我的应用服务器到Android设备。

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



这是我的代码:

pre $ public $ sendNotification(String messageBody)
{
尝试
{
网址=新网址(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;

字符串凭证=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 \:\这是我的标题 };
String dataStr ={\key1 \:\value1 \,\key2 \:\value2 \};

字符串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())));

字符串输出;
System.out.println(从服务器.... \\\
输出); ((output = br.readLine())!= null){
System.out.println(output);
while
}

conn.disconnect();

catch(Exception e)
{
e.printStackTrace();






$ p我得到的回应码是401, ...我猜凭证的格式是错误的...

json字符串是有效的json格式,所以我不打扰使用JSONObject。 p>

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

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

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



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

解决方案



pre $ public class FCMNotification {

//将通知从服务器发送到客户端的方法。
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; //你FCM AUTH键
字符串FMCurl = API_URL_FCM;

URL url =新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标题); //通知标题
info.put(body,Hello First Test notification); //通知主体
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(); ((inputLine = in.readLine())!= null){
response.append(inputLine);


}
in.close();


$ b @SuppressWarnings(static-access)
public static void main(String [] args)throws Exception {
FCMNotification obj =新的FCMNotification();
obj.pushFCMNotification(
USER_DEVICE_TOKEN);
}
}


I am struggling with the new FCM... I used FCM before, now I am trying FCM...

I am trying to send push notification for my app server to android device.

I wanna use the standard Java package, try not to use others such as Vert.x, apache's httpClient etc...

here is my code:

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

the response code i got is 401, which means unauthorized... i guess the format of credential is wrong...

The json string is in valid json format, so i don't bother to use JSONObject.

For the string credentials, i have tried "key:" + apiKey; but still got the same result.

The apiKey String is copied from the google-services.json I downloaded from Firebase console in google.

google didn't give a good example... just gave me this: https://firebase.google.com/docs/cloud-messaging/downstream

If any one knows how to do it, please reply. Thanks!!

解决方案

FULL EXAMPLE USE THIS FOR SEND NOTIFICATION USING 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");
    }
}

这篇关于在Java中将推送通知从服务器发送到Android设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆