使用SseEmitter时媒体类型不可接受

时间:2019-06-17 16:20:04

标签: spring-boot

在完成this教程之后,我正在尝试设置Sse Emitter。当我打开html页面时,我会得到

Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

在客户端(javascript)上说无法连接到服务器。我尝试了其他各种教程,但是对于为什么我的代码无法正常工作,我一无所知。

我建立了一个干净的测试项目,仅包含且完全包含教程代码。

1 个答案:

答案 0 :(得分:0)

当我遇到相同的问题时,我正在做其他事情。 下面的代码将其修复。

只需输入不匹配的媒体类型。

@GetMapping(value = "/api/push/notification",headers = "Accept=*/*", consumes = MediaType.ALL_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public String doNotify(@RequestParam("authToken") String token, @RequestParam("clientId") String clientId, HttpServletResponse response) throws InterruptedException, IOException {
    response.addHeader("charset","UTF-8");
    final SseEmitter emitter = new SseEmitter(30000l);
        service.addEmitter(clientId,emitter);
        service.sendConnectedNotification(clientId);
        emitter.onCompletion(() -> service.removeEmitter(clientId));
        emitter.onTimeout(() -> service.removeEmitter(clientId));
    return "Connected OK";
}

任何我的事件处理程序

 @Async
public void doNotify(String clientId, Object data) {
    SseEmitter emitter= emitters.get(clientId);
    if(emitter!=null) {
        try {
            emitter .send(SseEmitter.event() .reconnectTime(30000)
                .data(data,MediaType.APPLICATION_JSON)
                .id(UUID.randomUUID().toString())
                .name("Notification")
                .comment("Client connection notification")
            );
        } catch (Exception e) {
            emitters.remove(clientId);
        }
    }
}
相关问题