您好,欢迎访问三七文档
基于httpcore(httpclientcomponent)搭建轻量级http服务器下面是apache官网例子服务器端接受请求,实现接收文件请求处理器importjava.io.File;importjava.io.IOException;importjava.io.InterruptedIOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.net.URL;importjava.net.URLDecoder;importjava.nio.charset.Charset;importjava.security.KeyStore;importjava.util.Locale;importorg.apache.http.ConnectionClosedException;importorg.apache.http.HttpConnectionFactory;importorg.apache.http.HttpEntity;importorg.apache.http.HttpEntityEnclosingRequest;importorg.apache.http.HttpException;importorg.apache.http.HttpRequest;importorg.apache.http.HttpResponse;importorg.apache.http.HttpServerConnection;importorg.apache.http.HttpStatus;importorg.apache.http.MethodNotSupportedException;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.FileEntity;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.DefaultBHttpServerConnection;importorg.apache.http.impl.DefaultBHttpServerConnectionFactory;importorg.apache.http.protocol.BasicHttpContext;importorg.apache.http.protocol.HttpContext;importorg.apache.http.protocol.HttpProcessor;importorg.apache.http.protocol.HttpProcessorBuilder;importorg.apache.http.protocol.HttpRequestHandler;importorg.apache.http.protocol.HttpService;importorg.apache.http.protocol.ResponseConnControl;importorg.apache.http.protocol.ResponseContent;importorg.apache.http.protocol.ResponseDate;importorg.apache.http.protocol.ResponseServer;importorg.apache.http.protocol.UriHttpRequestHandlerMapper;importorg.apache.http.util.EntityUtils;importjavax.net.ssl.KeyManager;importjavax.net.ssl.KeyManagerFactory;importjavax.net.ssl.SSLContext;importjavax.net.ssl.SSLServerSocketFactory;/***Basic,yetfullyfunctionalandspeccompliant,HTTP/1.1fileserver.*/publicclassElementalHttpServer{publicstaticvoidmain(String[]args)throwsException{if(args.length1){System.err.println(Pleasespecifydocumentrootdirectory);System.exit(1);}//DocumentrootdirectoryStringdocRoot=args[0];intport=8080;if(args.length=2){port=Integer.parseInt(args[1]);}//SetuptheHTTPprotocolprocessorHttpProcessorhttpproc=HttpProcessorBuilder.create().add(newResponseDate()).add(newResponseServer(Test/1.1)).add(newResponseContent()).add(newResponseConnControl()).build();//SetuprequesthandlersUriHttpRequestHandlerMapperreqistry=newUriHttpRequestHandlerMapper();reqistry.register(*,newHttpFileHandler(docRoot));//SetuptheHTTPserviceHttpServicehttpService=newHttpService(httpproc,reqistry);SSLServerSocketFactorysf=null;if(port==8443){//InitializeSSLcontextClassLoadercl=ElementalHttpServer.class.getClassLoader();URLurl=cl.getResource(my.keystore);if(url==null){System.out.println(Keystorenotfound);System.exit(1);}KeyStorekeystore=KeyStore.getInstance(jks);keystore.load(url.openStream(),secret.toCharArray());KeyManagerFactorykmfactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());kmfactory.init(keystore,secret.toCharArray());KeyManager[]keymanagers=kmfactory.getKeyManagers();SSLContextsslcontext=SSLContext.getInstance(TLS);sslcontext.init(keymanagers,null,null);sf=sslcontext.getServerSocketFactory();}Threadt=newRequestListenerThread(port,httpService,sf);t.setDaemon(false);t.start();}staticclassHttpFileHandlerimplementsHttpRequestHandler{privatefinalStringdocRoot;publicHttpFileHandler(finalStringdocRoot){super();this.docRoot=docRoot;}publicvoidhandle(finalHttpRequestrequest,finalHttpResponseresponse,finalHttpContextcontext)throwsHttpException,IOException{Stringmethod=request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);if(!method.equals(GET)&&!method.equals(HEAD)&&!method.equals(POST)){thrownewMethodNotSupportedException(method+methodnotsupported);}Stringtarget=request.getRequestLine().getUri();if(requestinstanceofHttpEntityEnclosingRequest){HttpEntityentity=((HttpEntityEnclosingRequest)request).getEntity();byte[]entityContent=EntityUtils.toByteArray(entity);System.out.println(Incomingentitycontent(bytes):+entityContent.length);}finalFilefile=newFile(this.docRoot,URLDecoder.decode(target,UTF-8));if(!file.exists()){response.setStatusCode(HttpStatus.SC_NOT_FOUND);StringEntityentity=newStringEntity(htmlbodyh1File+file.getPath()+notfound/h1/body/html,ContentType.create(text/html,UTF-8));response.setEntity(entity);System.out.println(File+file.getPath()+notfound);}elseif(!file.canRead()||file.isDirectory()){response.setStatusCode(HttpStatus.SC_FORBIDDEN);StringEntityentity=newStringEntity(htmlbodyh1Accessdenied/h1/body/html,ContentType.create(text/html,UTF-8));response.setEntity(entity);System.out.println(Cannotreadfile+file.getPath());}else{response.setStatusCode(HttpStatus.SC_OK);FileEntitybody=newFileEntity(file,ContentType.create(text/html,(Charset)null));response.setEntity(body);System.out.println(Servingfile+file.getPath());}}}staticclassRequestListenerThreadextendsThread{privatefinalHttpConnectionFactoryDefaultBHttpServerConnectionconnFactory;privatefinalServerSocketserversocket;privatefinalHttpServicehttpService;publicReq
本文标题:基于httpcore(httpclientcomponent)搭建轻量级http服务器
链接地址:https://www.777doc.com/doc-2569963 .html