package io.geekidea.springbootplus.test;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class FirebaseTest {


    public static void main(String[] args) {
        String to = "";

        String key = "";

        String jsonStr = null;
        try {
            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("POST");
            //不设置默认发送文本格式。设置就是json
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "key=" + key);
            JSONObject json = new JSONObject();
            //推送到哪台客户端机器
            json.put("to", to);
            JSONObject info = new JSONObject();
            info.put("title", "新消息");
            info.put("body", "点击查看");
            //数据消息data  通知消息 notification
            json.put("notification", info);

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            jsonStr = json.toString();
            wr.write(jsonStr);
            wr.flush();
            InputStream inputStream = conn.getInputStream();
            InputStreamReader in = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(in);
//            String line = null;

            wr.close();
            reader.close();
        } catch (Exception e) {
            log.error("FCM push failure: " + jsonStr, e);
        }
    }
}

