基于httpcorehttpclient component搭建轻量级http服务器.docx
《基于httpcorehttpclient component搭建轻量级http服务器.docx》由会员分享,可在线阅读,更多相关《基于httpcorehttpclient component搭建轻量级http服务器.docx(15页珍藏版)》请在冰豆网上搜索。
基于httpcorehttpclientcomponent搭建轻量级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();
HttpRequestExecutorhttpexecutor=newHttpRequestExecutor();
HttpCoreContextcoreContext=HttpCoreContext.create();
HttpHosthost=newHttpHost("localhost",8080);
coreContext.setTargetHost(host);
DefaultBHttpClientConnectionconn=newDefaultBHttpClientConnection(8*1024);
ConnectionReuseStrategyconnStrategy=DefaultConnectionReuseStrategy.INSTANCE;
try{
String[]targets={
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};
for(inti=0;iif(!
conn.isOpen()){
Socketsocket=newSocket(host.getHostName(),host.getPort());
conn.bind(socket);
}
BasicHttpRequestrequest=newBasicHttpRequest("GET",targets[i]);
System.out.println(">>RequestURI:
"+request.getRequestLine().getUri());
httpexecutor.preProcess(request,httpproc,coreContext);
HttpResponseresponse=httpexecutor.execute(request,conn,coreContext);
httpexecutor.postProcess(response,httpproc,coreContext);
System.out.println("<"