ANDROID

fcm 서블릿(JSP) 참고

장꾸꾸 2021. 1. 11. 16:42
@WebServlet(name = "Fcm", urlPatterns = { "/fcm" })
public class FcmServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
      
      response.setContentType("application/x-json; charset=UTF-8");

      response.getWriter().print("ahahahahah");
   }

   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {   
        String token = "dhhOXrrRTsqB-33xDkzbqu:APA91bG2goIYICEiV5YqNdG5vFsUW435AjAP6uKCPKCUwgRKvOwEZp4Cd_2Lkp70erB1tzoWShNhOAOAM6PVouhWag2tnef4jDek67GTy_xxZou5PmQfem6XFZ1n_vcBoQuZfW8WqcLo";
        String token2 = "dd_FlieDSXaM67NSJnHiGY:APA91bGM3fEke28DO0HzJ_Hz_idADm58s0Zvtiuw1XyFlJ2O4WJPDYfA-h0kaVdvTc7JcAwCS2gQpCDlqSMKXFpYm2ve-B12EL47uUhibeB89MXRYy9HjaYCt_jDR5pBGBGtElL_icIH";
        ArrayList<String> idsArr = new ArrayList<String>(); //푸시를 보낼 디바이스 토큰들
        idsArr.add(token);
//        idsArr.add(token2);     
        
        final String apiKey = "자신의 서버키";
        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);
        conn.setDoOutput(true);

        // 이렇게 보내면 주제를 ALL로 지정해놓은 모든 사람들한테 알림을 날려준다.
//        String input = "{\"notification\" : {\"title\" : \"여기다 제목 넣기 \", \"body\" : \"여기다 내용 넣기\"}, \"to\":\"/topics/ALL\"}";
        
        
        String jsonArr = "[";          
        for (int i = 0; i < idsArr.size(); i++) {
           if(i== idsArr.size()-1) {
              jsonArr+= "\""+idsArr.get(i)+"\"]";
           }else {
              jsonArr+= "\""+idsArr.get(i)+"\",";              
           }
      }
        
        String title = "아하하하";
        String cotent = "내요요요요요요요용";
        String input = "{\"notification\" : "
              +          "{\"title\" : \" "+title+" \","
              + "           \"body\" : \""+cotent+"\"},"
              + "           \"registration_ids\":"+ jsonArr +"}";        
       
        
        OutputStream os = conn.getOutputStream();
        
        // 서버에서 날려서 한글 깨지는 사람은 아래처럼  UTF-8로 인코딩해서 날려주자
        os.write(input.getBytes("UTF-8"));        
        os.flush();        
        os.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + input);
        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();
        // print result
        System.out.println(response.toString());        

   }
}