Search code examples
javaservletsrestlet

HttpServletResponse won't stream bytes to client


I've been trying to figure out why the Servlet won't return the bytes to the client with this code (although the bytes is read based on the logs):

Redirector redirector = new SelfInjectingRedirector(getContext(), targetPattern,
        Redirector.MODE_SERVER_OUTBOUND){

    @Inject
    FileStore fileStore;

    String fileName = "something_for_sample";
    boolean isBufferFirst = true;

    @Override
    public void handle(Request request, Response response) {
        try {
            HttpServletRequest servletRequest = ServletUtils.getRequest(request);
            HttpServletResponse servletResponse = ServletUtils.getResponse(response);
            //
            // Either statement here wont return the bytes to the client
            // 
            if(isBufferFirst) {
                byte[] bytes = fileStore.get(fileName);
                System.out.println("Bytes read: " + bytes.length); // Bytes read: 5731
                servletResponse.getOutputStream().write(bytes, 0, bytes.length)
            } else {
                fileStore.get(fileName, servletResponse.getOutputStream());
            }
        } catch (Exception e) {
            response.setStatus(Status.SERVER_ERROR_INTERNAL);
            e.printStackTrace();
        }
        System.out.println("Handle Done");
    }

};

Solution

  • The solution is to add the "Content-Length" header.