Code example for HttpResponse

Methods: setEntity, setStatusCode

0
 
            String target = request.getRequestLine().getUri();
            final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
            if (!file.exists()) {
 
                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                NStringEntity entity = new NStringEntity(
                        "<html><body><h1>File" + file.getPath() +
                        " not found</h1></body></html>", "UTF-8"); 
                entity.setContentType("text/html; charset=UTF-8");
                response.setEntity(entity);
                System.out.println("File " + file.getPath() + " not found");
 
            } else if (!file.canRead() || file.isDirectory()) {
 
                response.setStatusCode(HttpStatus.SC_FORBIDDEN);
                NStringEntity entity = new NStringEntity(
                        "<html><body><h1>Access denied</h1></body></html>", 
                        "UTF-8"); 
                entity.setContentType("text/html; charset=UTF-8");
                response.setEntity(entity);
                System.out.println("Cannot read file " + file.getPath());
 
            } else { 
 
                response.setStatusCode(HttpStatus.SC_OK);
                NFileEntity body = new NFileEntity(file, "text/html");
                response.setEntity(body);
                System.out.println("Serving file " + file.getPath());
 
            } 
        }