Java/Android 实现简单的HTTP服务器
目前在对Android的代码进行功能测试的时候,需要服务器返回一个数据来测试整个流程是否正确。不希望引入第三方的JAR包,因此需要一个特别简单的HTTP服务器。
网上查询了一下,找到可用的代码如下:
importjava.io.BufferedOutputStream;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.Date;
importjava.util.StringTokenizer;
//ThetutorialcanbefoundjusthereontheSSaurel'sBlog:
//https://www.ssaurel.com/blog/create-a-simple-http-web-server-in-java
//EachClientConnectionwillbemanagedinadedicatedThread
publicclassJavaHTTPServerimplementsRunnable{
staticfinalFileWEB_ROOT=newFile(".");
staticfinalStringDEFAULT_FILE="index.html";
staticfinalStringFILE_NOT_FOUND="404.html";
staticfinalStringMETHOD_NOT_SUPPORTED="not_supported.html";
//porttolistenconnection
staticfinalintPORT=8080;
//verbosemode
staticfinalbooleanverbose=true;
//ClientConnectionviaSocketClass
privateSocketconnect;
publicJavaHTTPServer(Socketc){
connect=c;
}
publicstaticvoidmain(String[]args){
try{
ServerSocketserverConnect=newServerSocket(PORT);
System.out.println("Serverstarted.\nListeningforconnectionsonport:"+PORT+"...\n");
//welistenuntiluserhaltsserverexecution
while(true){
JavaHTTPServermyServer=newJavaHTTPServer(serverConnect.accept());
if(verbose){
System.out.println("Connectonopened.("+newDate()+")");
}
//creatededicatedthreadtomanagetheclientconnection
Threadthread=newThread(myServer);
thread.start();
}
}catch(IOExceptione){
System.err.println("ServerConnectionerror:"+e.getMessage());
}
}
@Override
publicvoidrun(){
//wemanageourparticularclientconnection
BufferedReaderin=null;PrintWriterout=null;BufferedOutputStreamdataOut=null;
StringfileRequested=null;
try{
//wereadcharactersfromtheclientviainputstreamonthesocket
in=newBufferedReader(newInputStreamReader(connect.getInputStream()));
//wegetcharacteroutputstreamtoclient(forheaders)
out=newPrintWriter(connect.getOutputStream());
//getbinaryoutputstreamtoclient(forrequesteddata)
dataOut=newBufferedOutputStream(connect.getOutputStream());
//getfirstlineoftherequestfromtheclient
Stringinput=in.readLine();
//weparsetherequestwithastringtokenizer
StringTokenizerparse=newStringTokenizer(input);
Stringmethod=parse.nextToken().toUpperCase();//wegettheHTTPmethodoftheclient
//wegetfilerequested
fileRequested=parse.nextToken().toLowerCase();
//wesupportonlyGETandHEADmethods,wecheck
if(!method.equals("GET")&&!method.equals("HEAD")){
if(verbose){
System.out.println("501NotImplemented:"+method+"method.");
}
//wereturnthenotsupportedfiletotheclient
Filefile=newFile(WEB_ROOT,METHOD_NOT_SUPPORTED);
intfileLength=(int)file.length();
StringcontentMimeType="text/html";
//readcontenttoreturntoclient
byte[]fileData=readFileData(file,fileLength);
//wesendHTTPHeaderswithdatatoclient
out.println("HTTP/1.1501NotImplemented");
out.println("Server:JavaHTTPServerfromSSaurel:1.0");
out.println("Date:"+newDate());
out.println("Content-type:"+contentMimeType);
out.println("Content-length:"+fileLength);
out.println();//blanklinebetweenheadersandcontent,veryimportant!
out.flush();//flushcharacteroutputstreambuffer
//file
dataOut.write(fileData,0,fileLength);
dataOut.flush();
}else{
//GETorHEADmethod
if(fileRequested.endsWith("/")){
fileRequested+=DEFAULT_FILE;
}
Filefile=newFile(WEB_ROOT,fileRequested);
intfileLength=(int)file.length();
Stringcontent=getContentType(fileRequested);
if(method.equals("GET")){//GETmethodsowereturncontent
byte[]fileData=readFileData(file,fileLength);
//sendHTTPHeaders
out.println("HTTP/1.1200OK");
out.println("Server:JavaHTTPServerfromSSaurel:1.0");
out.println("Date:"+newDate());
out.println("Content-type:"+content);
out.println("Content-length:"+fileLength);
out.println();//blanklinebetweenheadersandcontent,veryimportant!
out.flush();//flushcharacteroutputstreambuffer
dataOut.write(fileData,0,fileLength);
dataOut.flush();
}
if(verbose){
System.out.println("File"+fileRequested+"oftype"+content+"returned");
}
}
}catch(FileNotFoundExceptionfnfe){
try{
fileNotFound(out,dataOut,fileRequested);
}catch(IOExceptionioe){
System.err.println("Errorwithfilenotfoundexception:"+ioe.getMessage());
}
}catch(IOExceptionioe){
System.err.println("Servererror:"+ioe);
}finally{
try{
in.close();
out.close();
dataOut.close();
connect.close();//weclosesocketconnection
}catch(Exceptione){
System.err.println("Errorclosingstream:"+e.getMessage());
}
if(verbose){
System.out.println("Connectionclosed.\n");
}
}
}
privatebyte[]readFileData(Filefile,intfileLength)throwsIOException{
FileInputStreamfileIn=null;
byte[]fileData=newbyte[fileLength];
try{
fileIn=newFileInputStream(file);
fileIn.read(fileData);
}finally{
if(fileIn!=null)
fileIn.close();
}
returnfileData;
}
//returnsupportedMIMETypes
privateStringgetContentType(StringfileRequested){
if(fileRequested.endsWith(".htm")||fileRequested.endsWith(".html"))
return"text/html";
else
return"text/plain";
}
privatevoidfileNotFound(PrintWriterout,OutputStreamdataOut,StringfileRequested)throwsIOException{
Filefile=newFile(WEB_ROOT,FILE_NOT_FOUND);
intfileLength=(int)file.length();
Stringcontent="text/html";
byte[]fileData=readFileData(file,fileLength);
out.println("HTTP/1.1404FileNotFound");
out.println("Server:JavaHTTPServerfromSSaurel:1.0");
out.println("Date:"+newDate());
out.println("Content-type:"+content);
out.println("Content-length:"+fileLength);
out.println();//blanklinebetweenheadersandcontent,veryimportant!
out.flush();//flushcharacteroutputstreambuffer
dataOut.write(fileData,0,fileLength);
dataOut.flush();
if(verbose){
System.out.println("File"+fileRequested+"notfound");
}
}
}
以上就是Java/Android实现简单的HTTP服务器的详细内容,更多关于Java/AndroidHTTP服务器的资料请关注毛票票其它相关文章!