org.apache.http.protocol.HttpService

/*
    2    * $HeadURL: https://svn.apache.org/repos/asf/httpcomponents/httpcore/tags/4.0.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java $
    3    * $Revision: 744516 $
    4    * $Date: 2009-02-14 17:38:14 +0100 (Sat, 14 Feb 2009) $
    5    *
    6    * ====================================================================
    7    * Licensed to the Apache Software Foundation (ASF) under one
    8    * or more contributor license agreements.  See the NOTICE file
    9    * distributed with this work for additional information
   10    * regarding copyright ownership.  The ASF licenses this file
   11    * to you under the Apache License, Version 2.0 (the
   12    * "License"); you may not use this file except in compliance
   13    * with the License.  You may obtain a copy of the License at
   14    *
   15    *   http://www.apache.org/licenses/LICENSE-2.0
   16    *
   17    * Unless required by applicable law or agreed to in writing,
   18    * software distributed under the License is distributed on an
   19    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   20    * KIND, either express or implied.  See the License for the
   21    * specific language governing permissions and limitations
   22    * under the License.
   23    * ====================================================================
   24    *
   25    * This software consists of voluntary contributions made by many
   26    * individuals on behalf of the Apache Software Foundation.  For more
   27    * information on the Apache Software Foundation, please see
   28    * .
   29    *
   30    */
   31  
   32   package org.apache.http.examples;
   33  
   34   import java.io.File;
   35   import java.io.IOException;
   36   import java.io.InterruptedIOException;
   37   import java.io.OutputStream;
   38   import java.io.OutputStreamWriter;
   39   import java.net.ServerSocket;
   40   import java.net.Socket;
   41   import java.net.URLDecoder;
   42   import java.util.Locale;
   43  
   44   import org.apache.http.ConnectionClosedException;
   45   import org.apache.http.HttpEntity;
   46   import org.apache.http.HttpEntityEnclosingRequest;
   47   import org.apache.http.HttpException;
   48   import org.apache.http.HttpRequest;
   49   import org.apache.http.HttpResponse;
   50   import org.apache.http.HttpServerConnection;
   51   import org.apache.http.HttpStatus;
   52   import org.apache.http.MethodNotSupportedException;
   53   import org.apache.http.entity.ContentProducer;
   54   import org.apache.http.entity.EntityTemplate;
   55   import org.apache.http.entity.FileEntity;
   56   import org.apache.http.impl.DefaultConnectionReuseStrategy;
   57   import org.apache.http.impl.DefaultHttpResponseFactory;
   58   import org.apache.http.impl.DefaultHttpServerConnection;
   59   import org.apache.http.params.BasicHttpParams;
   60   import org.apache.http.params.CoreConnectionPNames;
   61   import org.apache.http.params.HttpParams;
   62   import org.apache.http.params.CoreProtocolPNames;
   63   import org.apache.http.protocol.BasicHttpProcessor;
   64   import org.apache.http.protocol.HttpContext;
   65   import org.apache.http.protocol.BasicHttpContext;
   66   import org.apache.http.protocol.HttpRequestHandler;
   67   import org.apache.http.protocol.HttpRequestHandlerRegistry;
   68   import org.apache.http.protocol.HttpService;
   69   import org.apache.http.protocol.ResponseConnControl;
   70   import org.apache.http.protocol.ResponseContent;
   71   import org.apache.http.protocol.ResponseDate;
   72   import org.apache.http.protocol.ResponseServer;
   73   import org.apache.http.util.EntityUtils;
   74  
   75   /**
   76    * Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
   77    *


   78    * Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
   79    * It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
   80    *
   81    *
   82    * @version $Revision: 744516 $
   83    */
   84   public class ElementalHttpServer {
   85  
   86       public static void main(String[] args) throws Exception {
   87           if (args.length < 1) {
   88               System.err.println("Please specify document root directory");
   89               System.exit(1);
   90           }
   91           Thread t = new RequestListenerThread(8080, args[0]);
   92           t.setDaemon(false);
   93           t.start();
   94       }
   95      
   96       static class HttpFileHandler implements HttpRequestHandler  {
   97          
   98           private final String docRoot;
   99          
  100           public HttpFileHandler(final String docRoot) {
  101               super();
  102               this.docRoot = docRoot;
  103           }
  104          
  105           public void handle(
  106                   final HttpRequest request,
  107                   final HttpResponse response,
  108                   final HttpContext context) throws HttpException, IOException {
  109  
  110               String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
  111               if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
  112                   throw new MethodNotSupportedException(method + " method not supported");
  113               }
  114               String target = request.getRequestLine().getUri();
  115  
  116               if (request instanceof HttpEntityEnclosingRequest) {
  117                   HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
  118                   byte[] entityContent = EntityUtils.toByteArray(entity);
  119                   System.out.println("Incoming entity content (bytes): " + entityContent.length);
  120               }
  121              
  122               final File file = new File(this.docRoot, URLDecoder.decode(target));
  123               if (!file.exists()) {
  124  
  125                   response.setStatusCode(HttpStatus.SC_NOT_FOUND);
  126                   EntityTemplate body = new EntityTemplate(new ContentProducer() {
  127                      
  128                       public void writeTo(final OutputStream outstream) throws IOException {
  129                           OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
  130                           writer.write("

");
  131                           writer.write("File ");
  132                           writer.write(file.getPath());
  133                           writer.write(" not found");
  134                           writer.write("

");
  135                           writer.flush();
  136                       }
  137                      
  138                   });
  139                   body.setContentType("text/html; charset=UTF-8");
  140                   response.setEntity(body);
  141                   System.out.println("File " + file.getPath() + " not found");
  142                  
  143               } else if (!file.canRead() || file.isDirectory()) {
  144                  
  145                   response.setStatusCode(HttpStatus.SC_FORBIDDEN);
  146                   EntityTemplate body = new EntityTemplate(new ContentProducer() {
  147                      
  148                       public void writeTo(final OutputStream outstream) throws IOException {
  149                           OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
  150                           writer.write("

");
  151                           writer.write("Access denied");
  152                           writer.write("

");
  153                           writer.flush();
  154                       }
  155                      
  156                   });
  157                   body.setContentType("text/html; charset=UTF-8");
  158                   response.setEntity(body);
  159                   System.out.println("Cannot read file " + file.getPath());
  160                  
  161               } else {
  162                  
  163                   response.setStatusCode(HttpStatus.SC_OK);
  164                   FileEntity body = new FileEntity(file, "text/html");
  165                   response.setEntity(body);
  166                   System.out.println("Serving file " + file.getPath());
  167                  
  168               }
  169           }
  170          
  171       }
  172      
  173       static class RequestListenerThread extends Thread {
  174  
  175           private final ServerSocket serversocket;
  176           private final HttpParams params;
  177           private final HttpService httpService;
  178          
  179           public RequestListenerThread(int port, final String docroot) throws IOException {
  180               this.serversocket = new ServerSocket(port);
  181               this.params = new BasicHttpParams();
  182               this.params
  183                   .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
  184                   .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
  185                   .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
  186                   .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
  187                   .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
  188  
  189               // Set up the HTTP protocol processor
  190               BasicHttpProcessor httpproc = new BasicHttpProcessor();
  191               httpproc.addInterceptor(new ResponseDate());
  192               httpproc.addInterceptor(new ResponseServer());
  193               httpproc.addInterceptor(new ResponseContent());
  194               httpproc.addInterceptor(new ResponseConnControl());
  195              
  196               // Set up request handlers
  197               HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
  198               reqistry.register("*", new HttpFileHandler(docroot));
  199              
  200               // Set up the HTTP service
  201               this.httpService = new HttpService(
  202                       httpproc,
  203                       new DefaultConnectionReuseStrategy(),
  204                       new DefaultHttpResponseFactory());
  205               this.httpService.setParams(this.params);
  206               this.httpService.setHandlerResolver(reqistry);
  207           }
  208          
  209           public void run() {
  210               System.out.println("Listening on port " + this.serversocket.getLocalPort());
  211               while (!Thread.interrupted()) {
  212                   try {
  213                       // Set up HTTP connection
  214                       Socket socket = this.serversocket.accept();
  215                       DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
  216                       System.out.println("Incoming connection from " + socket.getInetAddress());
  217                       conn.bind(socket, this.params);
  218  
  219                       // Start worker thread
  220                       Thread t = new WorkerThread(this.httpService, conn);
  221                       t.setDaemon(true);
  222                       t.start();
  223                   } catch (InterruptedIOException ex) {
  224                       break;
  225                   } catch (IOException e) {
  226                       System.err.println("I/O error initialising connection thread: "
  227                               + e.getMessage());
  228                       break;
  229                   }
  230               }
  231           }
  232       }
  233      
  234       static class WorkerThread extends Thread {
  235  
  236           private final HttpService httpservice;
  237           private final HttpServerConnection conn;
  238          
  239           public WorkerThread(
  240                   final HttpService httpservice,
  241                   final HttpServerConnection conn) {
  242               super();
  243               this.httpservice = httpservice;
  244               this.conn = conn;
  245           }
  246          
  247           public void run() {
  248               System.out.println("New connection thread");
  249               HttpContext context = new BasicHttpContext(null);
  250               try {
  251                   while (!Thread.interrupted() && this.conn.isOpen()) {
  252                       this.httpservice.handleRequest(this.conn, context);
  253                   }
  254               } catch (ConnectionClosedException ex) {
  255                   System.err.println("Client closed connection");
  256               } catch (IOException ex) {
  257                   System.err.println("I/O error: " + ex.getMessage());
  258               } catch (HttpException ex) {
  259                   System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
  260               } finally {
  261                   try {
  262                       this.conn.shutdown();
  263                   } catch (IOException ignore) {}
  264               }
  265           }
  266  
  267       }
  268      
  269   }

你可能感兴趣的:(org.apache.http.protocol.HttpService)