如何使用Spring Boot发送通知(FCM)

时间:2018-08-21 08:07:03

标签: spring firebase spring-boot firebase-cloud-messaging

我有一个API,当我更改名为“会议”的表中的内容时,我想向智能手机发送通知。为此,我正在创建一种POST类型的方法,该方法将以下 JSON正文以及授权密钥(由firebase提供)发送到以下URL https://fcm.googleapis.com/fcm/send

@Headers -> *******



 {
       "to": "/topics/groupNameChoosenByYou",
       "data": {
          "title": "Your title",
          "message": "Your message"
       }
    }

这是我的AndroidPushNotificationsService

@Service
public class AndroidPushNotificationsService {

    private static final String FIREBASE_SERVER_KEY = "AAAAq88vWWE:APA91bF5rSyqGbx26AY5jm6NsEfwJynQsnTd1MPFOTOz1ekTGZyof3Vz6gBb0769MLLxD7EXMcqKiPIHnqLh5buHEeUASnpsn-ltxR1J8z3kWJIAPNWlPZB0r0zKkXMyWkrbT3BLPWmCdi-NZnP3Jkb2z-QqtwJt5Q";
    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);
    }
}

这是我的HeaderRequestInterceptor

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);
    }
}

这是我的控制人

@RestController
public class WebController {

    private final String TOPIC = "test";

    @Autowired
    AndroidPushNotificationsService androidPushNotificationsService;

    @RequestMapping(value = "/send", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<String> send() throws JSONException {

        JSONObject body = new JSONObject();
        body.put("to", "/topics/" + TOPIC);
        body.put("priority", "high");

        JSONObject notification = new JSONObject();
        notification.put("title", "JSA Notification");
        notification.put("body", "Happy Message!");

        JSONObject data = new JSONObject();
        data.put("Key-1", "JSA Data 1");
        data.put("Key-2", "JSA Data 2");

        body.put("notification", notification);
        body.put("data", data);

        HttpEntity<String> request = new HttpEntity<>(body.toString());

        CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
        CompletableFuture.allOf(pushNotification).join();

        try {
            String firebaseResponse = pushNotification.get();

            return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

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

问题是,当我转到http://localhost:8080/springbootapi/send时,我得到了404,但是服务器正在运行。我想知道我的代码是否一切正常,因为FCM api需要POST方法,而在我的/ send方法中,我正在执行GET,所以基本上我是在创建一个API来调用其他api以便提供通知当表被更改时,对用户而言,这就是主要目的。有没有更好的方法来做到这一点,我们甚至是一个好习惯?

3 个答案:

答案 0 :(得分:0)

FCM需要POST,并且您要在restTemplate中发送POST。您的控制器是GET还是DELETE都没有关系。 但是ofc您应该将其设为POST,因为您正在发送某些内容,而不是进行检索。 404表示您输入的URL错误。它应该是: http://localhost:8080/send(如果您使用的是8080端口)

答案 1 :(得分:0)

确保您没有为Spring Boot应用程序设置任何上下文路径(Check log and search for Context path which might defined in Application.yml/properties)

如果您收到404,则端口8080可以正常使用,但请确保该端口仅由Spring引导应用程序打开(check the spring boot printed logs in console for port also)

我相信您的问题是,404错误不是由于FCM引起的,而是与您正在计算机中运行的应用程序有关。

答案 2 :(得分:0)

@RestController注释下方添加@RequestMapping("/springbootapi")或所需的任何路径。