Categories:
Audio (13)
Biotech (29)
Bytecode (35)
Database (77)
Framework (7)
Game (7)
General (512)
Graphics (53)
I/O (32)
IDE (2)
JAR Tools (86)
JavaBeans (16)
JDBC (89)
JDK (337)
JSP (20)
Logging (103)
Mail (54)
Messaging (8)
Network (71)
PDF (94)
Report (7)
Scripting (83)
Security (32)
Server (119)
Servlet (17)
SOAP (24)
Testing (50)
Web (19)
XML (301)
Other Resources:
Run HttpFileServer.java HttpComponents Core Example
How to run the HttpFileServer.java HttpComponents Core Example? I have httpcomponents-core-4.4.6-bin.zip installed.
✍: FYIcenter.com
If you have httpcomponents-core-4.4.6-bin.zip installed,
you can follow this tutorial to run the HttpFileServer.java HttpComponents Core Example:
1. Open the example program file HttpFileServer.java from \fyicenter\httpcomponents-core-4.4.6\examples\org\apache\http\examples\ folder:
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * ... */ package org.apache.http.examples; import java.io.File; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import org.apache.http.ConnectionClosedException; import org.apache.http.ExceptionLogger; import org.apache.http.HttpConnection; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.config.SocketConfig; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.bootstrap.HttpServer; import org.apache.http.impl.bootstrap.ServerBootstrap; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpCoreContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.ssl.SSLContexts; import org.apache.http.util.EntityUtils; /** * Embedded HTTP/1.1 file server based on a classic (blocking) I/O model. */ public class HttpFileServer { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Please specify document root directory"); System.exit(1); } // Document root directory String docRoot = args[0]; int port = 8080; if (args.length >= 2) { port = Integer.parseInt(args[1]); } SSLContext sslcontext = null; if (port == 8443) { // Initialize SSL context URL url = HttpFileServer.class.getResource("/my.keystore"); if (url == null) { System.out.println("Keystore not found"); System.exit(1); } sslcontext = SSLContexts.custom() .loadKeyMaterial(url, "secret".toCharArray(), "secret".toCharArray()) .build(); } SocketConfig socketConfig = SocketConfig.custom() .setSoTimeout(15000) .setTcpNoDelay(true) .build(); final HttpServer server = ServerBootstrap.bootstrap() .setListenerPort(port) .setServerInfo("Test/1.1") .setSocketConfig(socketConfig) .setSslContext(sslcontext) .setExceptionLogger(new StdErrorExceptionLogger()) .registerHandler("*", new HttpFileHandler(docRoot)) .create(); server.start(); server.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(5, TimeUnit.SECONDS); } }); } static class StdErrorExceptionLogger implements ExceptionLogger { @Override public void log(final Exception ex) { if (ex instanceof SocketTimeoutException) { System.err.println("Connection timed out"); } else if (ex instanceof ConnectionClosedException) { System.err.println(ex.getMessage()); } else { ex.printStackTrace(); } } } static class HttpFileHandler implements HttpRequestHandler { private final String docRoot; public HttpFileHandler(final String docRoot) { super(); this.docRoot = docRoot; } public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } String target = request.getRequestLine().getUri(); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); System.out.println("Incoming entity content (bytes): " + entityContent.length); } final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8")); if (!file.exists()) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); StringEntity entity = new StringEntity( "<html><body><h1>File" + file.getPath() + " not found</h1></body></html>", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("File " + file.getPath() + " not found"); } else if (!file.canRead() || file.isDirectory()) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); StringEntity entity = new StringEntity( "<html><body><h1>Access denied</h1></body></html>", ContentType.create("text/html", "UTF-8")); response.setEntity(entity); System.out.println("Cannot read file " + file.getPath()); } else { HttpCoreContext coreContext = HttpCoreContext.adapt(context); HttpConnection conn = coreContext.getConnection(HttpConnection.class); response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null)); response.setEntity(body); System.out.println(conn + ": serving file " + file.getPath()); } } } }
2. Compile and run the example with Java SE 8 JDK:
\fyicenter\httpcomponents-core-4.4.6\examples>\fyicenter\jdk-1.8.0\bin\javac -cp ..\lib\httpcore-4.4.6.jar org\apache\http\examples\HttpFileServer.java \fyicenter\httpcomponents-core-4.4.6\examples>\fyicenter\jdk-1.8.0\bin\java -cp .;..\lib\httpcore-4.4.6.jar org.apache.http.examples.HttpFileServer .
A HTTP server is running on port 8080 now, serving files from the \fyicenter\httpcomponents-core-4.4.6\examples folder.
Run a Web browser with http://localhost:8080, you will get an "Access denied" error, because you there is not file specified.
Run a Web browser with http://localhost:8080/org/apache/http/examples/PrintVersionInfo.java, you will get the content of PrintVersionInfo.java file.
Â
2017-11-02, 1354👍, 0💬
Popular Posts:
How to download and install ojdbc7.jar for Oracle 12c R1? ojdbc8.jar for Oracle 12c R1 is a Java 7 a...
The JMX technology provides the tools for building distributed, Web-based, modular and dynamic solut...
Commons Pool provides an Object-pooling API, with three major aspects: 1. A generic object pool inte...
XML Serializer, Release 2.7.1, allows you to write out XML, HTML etc. as a stream of characters from...
JLayer is a library that decodes/plays/converts MPEG 1/2/2.5 Layer 1/2/3 (i.e. MP3) in real time for...