谷歌fireBae推送

先上demo吧

@Value("${fcm.appkey}")
	String SERVER_KEY;
	private final String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
	Logger Log = LoggerFactory.getLogger(getClass());


	@Override
	public void pushMsg(PushBean pushBean, String deviceToken) {
		long startTime = 0;
		long endTime = 0;

		try {

			URL url = new URL(API_URL_FCM);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setUseCaches(false);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");

			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Accept", "application/json");
			conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
			JSONObject data=new JSONObject();
			data.put("to",deviceToken);
			JSONObject info = new JSONObject();
			info.put("title",pushBean.getTitle());   // Notification title
			info.put("content",pushBean.getText());
			info.put("body", pushBean.getExtMap()); // Notification body
			data.put("notification", info);
			try {
				OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
				wr.write(data.toString());
				wr.flush();

				BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream())));

				String output;
				StringBuilder builder = new StringBuilder();
				while ((output = br.readLine()) != null) {
					builder.append(output);
				}
				wr.close();
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			endTime = System.currentTimeMillis();
			Log.error("[fcmPushService] push msg Error, cost time = {} ", (endTime-startTime), e);
		}

附上文档:https://firebase.google.com/docs/cloud-messaging/http-server-ref?hl=zh-cn#params

你可能感兴趣的:(谷歌fireBae推送)