공부하는가비

[JAVA] FMC 웹 서버에서 안드로이드에 푸시 알림 보내기 본문

개발/Java

[JAVA] FMC 웹 서버에서 안드로이드에 푸시 알림 보내기

가비코코보리 2021. 11. 23. 10:44

1.프로젝트 구조 

 

2. FCM 사용하기 위해 dependency 추가 

   <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20160810</version>
   </dependency>
	<dependency>
		<groupId>com.google.firebase</groupId>
		<artifactId>firebase-admin</artifactId>
		<version>6.5.0</version>
	</dependency>

 

3.AndroidPushPeriodicNotifications

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class AndroidPushPeriodicNotifications {
	    
	    public String PeriodicNotificationJson() throws JSONException {
	        LocalDate localDate = LocalDate.now();
	        String sampleData[] = {"토큰1","토큰2"};    // 디바이스 토큰을 넣어주셔야 합니다. 
	        
	        List<String> tokenlist = new ArrayList<String>();
	        JSONObject body = new JSONObject();
	        JSONArray array = new JSONArray();
			
		    for(int i=0; i<sampleData.length; i++) { 
				  tokenlist.add(sampleData[i]); 
			}

	        for(int i=0; i<tokenlist.size(); i++) {
	        	array.put(tokenlist.get(i));
	        }  
			 
	        body.put("registration_ids",array);
	        body.put("priority", "high");
	        
	        JSONObject notification = new JSONObject();
	        notification.put("title","hello!");
	        notification.put("body","hello");

	        body.put("notification", notification);
	        System.out.println("##########body.toString()#########" +body.toString());
	        System.out.println(body.toString());

	        return body.toString();
	    }
	  
}

 

4. HeaderRequestInterceptor

 

import java.io.IOException;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;

public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor{
	  private final String headerName;
	  private final String headerValue;

	  public HeaderRequestInterceptor(String headerName, String headerValue) {
	      this.headerName = headerName;
	      this.headerValue = headerValue;
	  }

	  @Override
	  public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
	          throws IOException {
	      HttpRequest wrapper = new HttpRequestWrapper(request);
	      wrapper.getHeaders().set(headerName, headerValue);
	      return execution.execute(wrapper, body);
	  }
}

 

5.AndroidPushNotificationsService

 

import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;

import org.springframework.http.HttpEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import co.***.prj.pushapi.handle.HeaderRequestInterceptor;

@Service
public class AndroidPushNotificationsService {
    private static final String firebase_server_key="API키";
    private static final String firebase_api_url="https://fcm.googleapis.com/fcm/send";

    @Async
    public CompletableFuture<String> send(HttpEntity<String> entity) {

    	RestTemplate restTemplate = new RestTemplate();

        ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();

        interceptors.add(new HeaderRequestInterceptor("Authorization",  "key=" + firebase_server_key));
        interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json"));
        restTemplate.setInterceptors(interceptors);

        String firebaseResponse = restTemplate.postForObject(firebase_api_url, entity, String.class);

        return CompletableFuture.completedFuture(firebaseResponse);
    }
}

 

6.NotificationController

 

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import org.apache.ibatis.annotations.Param;
import org.apache.tiles.request.Request;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import co.***.prj.pushapi.handle.AndroidPushPeriodicNotifications;
import co.***.prj.pushapi.service.AndroidPushNotificationsService;

@RestController
public class NotificationController {

	Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AndroidPushNotificationsService androidPushNotificationsService;
    
    @GetMapping(value="/ipcam/alert/pushSend")
    public @ResponseBody ResponseEntity<String> send() throws JSONException, InterruptedException  {
    	AndroidPushPeriodicNotifications androidPushPeriodicNotifications = new AndroidPushPeriodicNotifications();
    	//받아오는 파라메터로 입력&수정&전송url 선택 
        String notifications = androidPushPeriodicNotifications.PeriodicNotificationJson();
        System.out.println("##########notifications#########" +notifications);

        HttpEntity<String> request = new HttpEntity<>(notifications);
        System.out.println("##########request#########" +request);
        CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
        CompletableFuture.allOf(pushNotification).join();

        try{
        	String firebaseResponse = pushNotification.get();
            return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
        }
        catch (InterruptedException e){
            logger.debug("got interrupted!");
            throw new InterruptedException();
        }
        catch (ExecutionException e){
            logger.debug("execution error!");
        }

        return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
    }
}

 

일단 난 토큰과 api 키 주소가 맞지 않아 

 

{"multicast_id":6357681101638783068,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

 

오류가 생긴다

'개발 > Java' 카테고리의 다른 글

[JAVA] Rest Api 호출 파라미터 정리  (0) 2021.11.24
Java Spring mysql 연동시 root.xml  (0) 2021.11.12
Spring security 참고  (0) 2021.10.21
Rest API 란  (0) 2021.10.18
2021.06.22 Spring 설문조사 Project  (0) 2021.06.22
Comments