搭建轻量级http服务器_第1页
搭建轻量级http服务器_第2页
搭建轻量级http服务器_第3页
搭建轻量级http服务器_第4页
搭建轻量级http服务器_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、下面是apache官网例子服务器端接受请求,实现接收文件请求处理器import java.io.File;import java.io.IOException;import java.io.InterruptedIOException;import .ServerSocket;import .Socket;import .URL;import .URLDecoder;import java.nio.charset.Charset;import java.security.KeyStore;import java.util.Locale;import org.apache.http.Connec

2、tionClosedException;import org.apache.http.HttpConnectionFactory;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.HttpServerConnection

3、;import org.apache.http.HttpStatus;import org.apache.http.MethodNotSupportedException;import org.apache.http.entity.ContentType;import org.apache.http.entity.FileEntity;import org.apache.http.entity.StringEntity;import org.apache.http.impl.DefaultBHttpServerConnection;import org.apache.http.impl.Def

4、aultBHttpServerConnectionFactory;import tocol.BasicHttpContext;import tocol.HttpContext;import tocol.HttpProcessor;import tocol.HttpProcessorBuilder;import tocol.HttpRequestHandler;import org.apache.http.p

5、rotocol.HttpService;import tocol.ResponseConnControl;import tocol.ResponseContent;import tocol.ResponseDate;import tocol.ResponseServer;import tocol.UriHttpRequestHandlerMapper;import org.apache.http.util.

6、EntityUtils;import .ssl.KeyManager;import .ssl.KeyManagerFactory;import .ssl.SSLContext;import .ssl.SSLServerSocketFactory;/* * Basic, yet fully functional and spec compliant, HTTP/1.1 file server. */public class ElementalHttpServer public static void main(String args) throws Exception if (args.leng

7、th < 1) System.err.println("Please specify document root directory"); System.exit(1); / Document root directory String docRoot = args0; int port = 8080; if (args.length >= 2) port = Integer.parseInt(args1); / Set up the HTTP protocol processor HttpProcessor httpproc = HttpProcessorBu

8、ilder.create() .add(new ResponseDate() .add(new ResponseServer("Test/1.1") .add(new ResponseContent() .add(new ResponseConnControl().build(); / Set up request handlers UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper(); reqistry.register("*", new HttpFileHan

9、dler(docRoot); / Set up the HTTP service HttpService httpService = new HttpService(httpproc, reqistry); SSLServerSocketFactory sf = null; if (port = 8443) / Initialize SSL context ClassLoader cl = ElementalHttpServer.class.getClassLoader(); URL url = cl.getResource("my.keystore"); if (url

10、= null) System.out.println("Keystore not found"); System.exit(1); KeyStore keystore = KeyStore.getInstance("jks"); keystore.load(url.openStream(), "secret".toCharArray(); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm(

11、); kmfactory.init(keystore, "secret".toCharArray(); KeyManager keymanagers = kmfactory.getKeyManagers(); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, null, null); sf = sslcontext.getServerSocketFactory(); Thread t = new RequestListenerThread

12、(port, httpService, sf); t.setDaemon(false); t.start(); 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, f

13、inal HttpContext context) throws HttpException, IOException String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") throw new MethodNotSupportedExcept

14、ion(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("

15、;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>

16、;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.isDir

17、ectory() 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.pri

18、ntln("Cannot read file " + file.getPath(); else response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, ContentType.create("text/html", (Charset) null); response.setEntity(body); System.out.println("Serving file " + file.getPath(); static class

19、RequestListenerThread extends Thread private final HttpConnectionFactory<DefaultBHttpServerConnection> connFactory; private final ServerSocket serversocket; private final HttpService httpService; public RequestListenerThread( final int port, final HttpService httpService, final SSLServerSocket

20、Factory sf) throws IOException this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE; this.serversocket = sf != null ? sf.createServerSocket(port) : new ServerSocket(port); this.httpService = httpService; Override public void run() System.out.println("Listening on port " + this.s

21、erversocket.getLocalPort(); while (!Terrupted() try / Set up HTTP connection Socket socket = this.serversocket.accept(); System.out.println("Incoming connection from " + socket.getInetAddress(); HttpServerConnection conn = this.connFactory.createConnection(socket); / Start worker

22、thread Thread t = new WorkerThread(this.httpService, conn); t.setDaemon(true); t.start(); catch (InterruptedIOException ex) break; catch (IOException e) System.err.println("I/O error initialising connection thread: " + e.getMessage(); break; static class WorkerThread extends Thread private

23、 final HttpService httpservice; private final HttpServerConnection conn; public WorkerThread( final HttpService httpservice, final HttpServerConnection conn) super(); this.httpservice = httpservice; this.conn = conn; Override public void run() System.out.println("New connection thread"); H

24、ttpContext context = new BasicHttpContext(null); try while (!Terrupted() && this.conn.isOpen() this.httpservice.handleRequest(this.conn, context); catch (ConnectionClosedException ex) System.err.println("Client closed connection"); catch (IOException ex) System.err.println

25、("I/O error: " + ex.getMessage(); catch (HttpException ex) System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage(); finally try this.conn.shutdown(); catch (IOException ignore) 客户端get请求实现类import .Socket;import org.apache.http.ConnectionReuseStrategy;import

26、org.apache.http.HttpHost;import org.apache.http.HttpResponse;import org.apache.http.impl.DefaultBHttpClientConnection;import org.apache.http.impl.DefaultConnectionReuseStrategy;import org.apache.http.message.BasicHttpRequest;import tocol.HttpCoreContext;import t

27、ocol.HttpProcessor;import tocol.HttpProcessorBuilder;import tocol.HttpRequestExecutor;import tocol.RequestConnControl;import tocol.RequestContent;import tocol.RequestExpectContinue;import org.apache.http.p

28、rotocol.RequestTargetHost;import tocol.RequestUserAgent;import org.apache.http.util.EntityUtils;/* * Elemental example for executing multiple GET requests sequentially. */public class ElementalHttpGet public static void main(String args) throws Exception HttpProcessor httpproc = H

29、ttpProcessorBuilder.create() .add(new RequestContent() .add(new RequestTargetHost() .add(new RequestConnControl() .add(new RequestUserAgent("Test/1.1") .add(new RequestExpectContinue(true).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext =

30、HttpCoreContext.create(); HttpHost host = new HttpHost("localhost", 8080); coreContext.setTargetHost(host); DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try String targets = &

31、quot;/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" for (int i = 0; i < targets.length; i+) if (!conn.isOpen() Socket socket = new Socket(host.getHostName(), host.getPort(); conn.bind(socket); BasicHttpRequest request = new BasicHttpRequest

32、("GET", targetsi); System.out.println(">> Request URI: " + request.getRequestLine().getUri(); httpexecutor.preProcess(request, httpproc, coreContext); HttpResponse response = httpexecutor.execute(request, conn, coreContext); httpexecutor.postProcess(response, httpproc, core

33、Context); System.out.println("<< Response: " + response.getStatusLine(); System.out.println(EntityUtils.toString(response.getEntity(); System.out.println("="); if (!connStrategy.keepAlive(response, coreContext) conn.close(); else System.out.println("Connection kept ali

34、ve."); finally conn.close(); 客户端post请求实现类import java.io.ByteArrayInputStream;import .Socket;import org.apache.http.ConnectionReuseStrategy;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.HttpResponse;import org.apache.http.e

35、ntity.ByteArrayEntity;import org.apache.http.entity.ContentType;import org.apache.http.entity.InputStreamEntity;import org.apache.http.entity.StringEntity;import org.apache.http.impl.DefaultBHttpClientConnection;import org.apache.http.impl.DefaultConnectionReuseStrategy;import org.apache.http.messag

36、e.BasicHttpEntityEnclosingRequest;import tocol.HttpCoreContext;import tocol.HttpProcessor;import tocol.HttpProcessorBuilder;import tocol.HttpRequestExecutor;import tocol.RequestConnControl;import org.apach

37、tocol.RequestContent;import tocol.RequestExpectContinue;import tocol.RequestTargetHost;import tocol.RequestUserAgent;import org.apache.http.util.EntityUtils;/* * Elemental example for executing multiple POST requests sequentially. */

38、public class ElementalHttpPost public static void main(String args) throws Exception HttpProcessor httpproc = HttpProcessorBuilder.create() .add(new RequestContent() .add(new RequestTargetHost() .add(new RequestConnControl() .add(new RequestUserAgent("Test/1.1") .add(new RequestExpectConti

39、nue(true).build(); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpCoreContext coreContext = HttpCoreContext.create(); HttpHost host = new HttpHost("localhost", 8080); coreContext.setTargetHost(host); DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024); ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE; try HttpEntity requestBodies = new StringEntity( "This is the first test request", ContentType.create("text/p

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论