Java Rest API: how to check connection between cli

2019-08-15 11:41发布

问题:

How I can check if user who sent rest request aborted it using Ctrl-C? I need to check it on server side because it takes several minutes. If user aborted it then I should stop it.

I tried to write to ServletOutputStream but it doesn't work (I never catch exception):

@Path("test")
public void test(@Context MessageContext mc) {
  try {
     ServletOutputStream out = mc.getHttpServletResponse().getOutputStream();
     out.println("test");
     out.flush();
  } catch (IOException e) {
     System.out.println("Connection is broken");
     return;
  }
}

Found solution:

    private boolean isConnected() {
    try {
        servletResponse.getOutputStream().println("data");
        servletResponse.flushBuffer();
        return true;
    } catch (IOException e) {
        return false;
    }
}

回答1:

private boolean isConnected() {
    try {
        servletResponse.getOutputStream().println("data");
        servletResponse.flushBuffer();
        return true;
    } catch (IOException e) {
        return false;
    }
}


标签: java rest jax-rs