FCMの通知リクエストをjavaで行なう

javaで通知リクエストを送る方法が日本語で見当たらないので書いてみました。

void fcm() throws Exception {
	HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send")
			.openConnection()));
	httpcon.setDoOutput(true);
	httpcon.setRequestProperty("Content-Type", "application/json");
	httpcon.setRequestProperty("Authorization", "key=SERVER-KEY");
	httpcon.setRequestMethod("POST");
	httpcon.connect();

	StringBuilder json = new StringBuilder();

	json.append("{");
	json.append("	\"to\" : \"/topics/test\",");
	json.append("	\"data\" : {");
	json.append("		\"id\" : 1,");
	json.append("		\"label\" : \"ラベル\",");
	json.append("		\"text\" : \"テキスト\"");
	json.append("	}");
	json.append("}");

	byte[] outputBytes = json.toString().getBytes("UTF-8");
	OutputStream os = httpcon.getOutputStream();
	os.write(outputBytes);
	os.close();

	// 送信確認(必須ではない)
	InputStream input = httpcon.getInputStream();
	BufferedReader reader = new BufferedReader(new InputStreamReader(input));

	for (String line; (line = reader.readLine()) != null;) {
		System.out.println(line);
	}
}

6行目のSERVER-KEYはFirebaseのサーバーキーに書き換えてください。



スポンサーサイト
アフィリエイトはエーハチネット
ドメイン取るならお名前.com

コメントを残す

メールアドレスが公開されることはありません。 ※ が付いている欄は必須項目です