基于httpcorehttpclient component搭建轻量级http服务器.docx

上传人:b****6 文档编号:6155980 上传时间:2023-01-04 格式:DOCX 页数:12 大小:48.89KB
下载 相关 举报
基于httpcorehttpclient component搭建轻量级http服务器.docx_第1页
第1页 / 共12页
基于httpcorehttpclient component搭建轻量级http服务器.docx_第2页
第2页 / 共12页
基于httpcorehttpclient component搭建轻量级http服务器.docx_第3页
第3页 / 共12页
基于httpcorehttpclient component搭建轻量级http服务器.docx_第4页
第4页 / 共12页
基于httpcorehttpclient component搭建轻量级http服务器.docx_第5页
第5页 / 共12页
点击查看更多>>
下载资源
资源描述

基于httpcorehttpclient component搭建轻量级http服务器.docx

《基于httpcorehttpclient component搭建轻量级http服务器.docx》由会员分享,可在线阅读,更多相关《基于httpcorehttpclient component搭建轻量级http服务器.docx(12页珍藏版)》请在冰豆网上搜索。

基于httpcorehttpclient component搭建轻量级http服务器.docx

基于httpcorehttpclientcomponent搭建轻量级http服务器

基于httpcore(httpclientcomponent)搭建轻量级http服务器

基于httpcore(httpclientcomponent)搭建轻量级http服务器

下面是apache官网例子

服务器端接受请求,实现接收文件请求处理器

importjava.io.File;

importjava.io.IOException;

importjava.io.InterruptedIOException;

import.ServerSocket;

import.Socket;

import.URL;

import.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;

import.ssl.KeyManager;

import.ssl.KeyManagerFactory;

import.ssl.SSLContext;

import.ssl.SSLServerSocketFactory;

/**

*Basic,yetfullyfunctionalandspeccompliant,HTTP/1.1fileserver.

*/

publicclassElementalHttpServer{

publicstaticvoidmain(String[]args)throwsException{

if(args.length<1){

System.err.println("Pleasespecifydocumentrootdirectory");

System.exit

(1);

}

//Documentrootdirectory

StringdocRoot=args[0];

intport=8080;

if(args.length>=2){

port=Integer.parseInt(args[1]);

}

//SetuptheHTTPprotocolprocessor

HttpProcessorhttpproc=HttpProcessorBuilder.create()

.add(newResponseDate())

.add(newResponseServer("Test/1.1"))

.add(newResponseContent())

.add(newResponseConnControl()).build();

//Setuprequesthandlers

UriHttpRequestHandlerMapperreqistry=newUriHttpRequestHandlerMapper();

reqistry.register("*",newHttpFileHandler(docRoot));

//SetuptheHTTPservice

HttpServicehttpService=newHttpService(httpproc,reqistry);

SSLServerSocketFactorysf=null;

if(port==8443){

//InitializeSSLcontext

ClassLoadercl=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(

"

File"+file.getPath()+

"notfound

",

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(

"

Accessdenied

",

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{

privatefinalHttpConnectionFactoryconnFactory;

privatefinalServerSocketserversocket;

privatefinalHttpServicehttpService;

publicRequestListenerThread(

finalintport,

finalHttpServicehttpService,

finalSSLServerSocketFactorysf)throwsIOException{

this.connFactory=DefaultBHttpServerConnectionFactory.INSTANCE;

this.serversocket=sf!

=null?

sf.createServerSocket(port):

newServerSocket(port);

this.httpService=httpService;

}

@Override

publicvoidrun(){

System.out.println("Listeningonport"+this.serversocket.getLocalPort());

while(!

Thread.interrupted()){

try{

//SetupHTTPconnection

Socketsocket=this.serversocket.accept();

System.out.println("Incomingconnectionfrom"+socket.getInetAddress());

HttpServerConnectionconn=this.connFactory.createConnection(socket);

//Startworkerthread

Threadt=newWorkerThread(this.httpService,conn);

t.setDaemon(true);

t.start();

}catch(InterruptedIOExceptionex){

break;

}catch(IOExceptione){

System.err.println("I/Oerrorinitialisingconnectionthread:

"

+e.getMessage());

break;

}

}

}

}

staticclassWorkerThreadextendsThread{

privatefinalHttpServicehttpservice;

privatefinalHttpServerConnectionconn;

publicWorkerThread(

finalHttpServicehttpservice,

finalHttpServerConnectionconn){

super();

this.httpservice=httpservice;

this.conn=conn;

}

@Override

publicvoidrun(){

System.out.println("Newconnectionthread");

HttpContextcontext=newBasicHttpContext(null);

try{

while(!

Thread.interrupted()&&this.conn.isOpen()){

this.httpservice.handleRequest(this.conn,context);

}

}catch(ConnectionClosedExceptionex){

System.err.println("Clientclosedconnection");

}catch(IOExceptionex){

System.err.println("I/Oerror:

"+ex.getMessage());

}catch(HttpExceptionex){

System.err.println("UnrecoverableHTTPprotocolviolation:

"+ex.getMessage());

}finally{

try{

this.conn.shutdown();

}catch(IOExceptionignore){}

}

}

}

}

客户端get请求实现类

import.Socket;

importorg.apache.http.ConnectionReuseStrategy;

importorg.apache.http.HttpHost;

importorg.apache.http.HttpResponse;

importorg.apache.http.impl.DefaultBHttpClientConnection;

importorg.apache.http.impl.DefaultConnectionReuseStrategy;

importorg.apache.http.message.BasicHttpRequest;

importorg.apache.http.protocol.HttpCoreContext;

importorg.apache.http.protocol.HttpProcessor;

importorg.apache.http.protocol.HttpProcessorBuilder;

importorg.apache.http.protocol.HttpRequestExecutor;

importorg.apache.http.protocol.RequestConnControl;

importorg.apache.http.protocol.RequestContent;

importorg.apache.http.protocol.RequestExpectContinue;

importorg.apache.http.protocol.RequestTargetHost;

importorg.apache.http.protocol.RequestUserAgent;

importorg.apache.http.util.EntityUtils;

/**

*ElementalexampleforexecutingmultipleGETrequestssequentially.

*/

publicclassElementalHttpGet{

publicstaticvoidmain(String[]args)throwsException{

HttpProcessorhttpproc=HttpProcessorBuilder.create()

.add(newRequestContent())

.add(newRequestTargetHost())

.add(newRequestConnControl())

.add(newRequestUserAgent("Test/1.1"))

.add(newRequestExpectContinue(true)).build();

System.out.println("Connectionkeptalive...");

}

}

}finally{

conn.close();

}

}

}

客户端post请求实现类

importjava.io.ByteArrayInputStream;

import.Socket;

importorg.apache.http.ConnectionReuseStrategy;

importorg.apache.http.Consts;

importorg.apache.http.HttpEntity;

importorg.apache.http.HttpHost;

importorg.apache.http.HttpResponse;

importorg.apache.http.entity.ByteArrayEntity;

importorg.apache.http.entity.ContentType;

importorg.apache.http.entity.InputStreamEntity;

importorg.apache.http.entity.StringEntity;

importorg.apache.http.impl.DefaultBHttpClientConnection;

importorg.apache.http.impl.DefaultConnectionReuseStrategy;

importorg.apache.http.message.BasicHttpEntityEnclosingRequest;

importorg.apache.http.protocol.HttpCoreContext;

importorg.apache.http.protocol.HttpProcessor;

importorg.apache.http.protocol.HttpProcessorBuilder;

importorg.apache.http.protocol.HttpRequestExecutor;

importorg.apache.http.p

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 自然科学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1