본문 바로가기
Programming/java

fcm push

by 막이 2020. 10. 16.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@RequestMapping(value = "/gn/push/send.do")
    public ResponseEntity<String> pushSend(@RequestParam Map<String,Object> commandMap, HttpServletRequest req, ModelMap model) throws Exception {
         //fcmService.send(request);
 
            JSONObject body = new JSONObject();
          body.put("to""디바이스 키 ");
            body.put("priority""high");
          
            
           JSONObject notification = new JSONObject();
           notification.put("body","내용");
           notification.put("title""제목");
           
           JSONObject data = new JSONObject();
           data.put("key1""value1");
           data.put("key2""value2");
 
           body.put("notification", notification);
           body.put("data", data);
         
 
           HttpEntity<String> request = new HttpEntity<>(body.toString());
 
           CompletableFuture<FirebaseResponse> pushNotification = androidPushNotificationsService.send(request);
           CompletableFuture.allOf(pushNotification).join();
 
           try {
               FirebaseResponse firebaseResponse = pushNotification.get();
               if (firebaseResponse.getSuccess() == 1) {
                   System.out.println("push notification sent ok!");
               } else {
                   System.out.println("error sending push notifications: " + firebaseResponse.toString());
               }
               return new ResponseEntity<>(firebaseResponse.toString(), HttpStatus.OK);
 
           } catch (InterruptedException e) {
               e.printStackTrace();
           } catch (ExecutionException e) {
               e.printStackTrace();
           }
        
           return new ResponseEntity<>("the push notification cannot be send.", HttpStatus.BAD_REQUEST);
    }
cs

 

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Service
public class AndroidPushNotificationsService {
 
    private static final String FIREBASE_SERVER_KEY = "KEY";
 
    @Async
    public CompletableFuture<FirebaseResponse> send(HttpEntity<String> entity) {
 
        RestTemplate restTemplate = new RestTemplate();
       restTemplate.getMessageConverters()
        .add(0new StringHttpMessageConverter(StandardCharsets.UTF_8));
 
        ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new HeaderRequestInterceptor("Authorization""key=" + FIREBASE_SERVER_KEY));
        interceptors.add(new HeaderRequestInterceptor("Content-Type""application/json; charset=utf-8"));
        restTemplate.setInterceptors(interceptors);
 
        FirebaseResponse firebaseResponse = restTemplate.postForObject("https://fcm.googleapis.com/fcm/send", entity, FirebaseResponse.class);
 
        return CompletableFuture.completedFuture(firebaseResponse);
    }
 
}
cs