欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java/Android 實現(xiàn)簡單的HTTP服務(wù)器

 更新時間:2020年10月21日 10:28:08   作者:默默的點滴  
這篇文章主要介紹了Java/Android 如何實現(xiàn)簡單的HTTP服務(wù)器,幫助大家更好的進行功能測試,感興趣的朋友可以了解下

目前在對Android的代碼進行功能測試的時候,需要服務(wù)器返回一個數(shù)據(jù)來測試整個流程是否正確。不希望引入第三方的JAR包,因此需要一個特別簡單的HTTP服務(wù)器。

網(wǎng)上查詢了一下,找到可用的代碼如下:

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.StringTokenizer;

// The tutorial can be found just here on the SSaurel's Blog : 
// https://www.ssaurel.com/blog/create-a-simple-http-web-server-in-java
// Each Client Connection will be managed in a dedicated Thread
public class JavaHTTPServer implements Runnable{ 
	
	static final File WEB_ROOT = new File(".");
	static final String DEFAULT_FILE = "index.html";
	static final String FILE_NOT_FOUND = "404.html";
	static final String METHOD_NOT_SUPPORTED = "not_supported.html";
	// port to listen connection
	static final int PORT = 8080;
	
	// verbose mode
	static final boolean verbose = true;
	
	// Client Connection via Socket Class
	private Socket connect;
	
	public JavaHTTPServer(Socket c) {
		connect = c;
	}
	
	public static void main(String[] args) {
		try {
			ServerSocket serverConnect = new ServerSocket(PORT);
			System.out.println("Server started.\nListening for connections on port : " + PORT + " ...\n");
			
			// we listen until user halts server execution
			while (true) {
				JavaHTTPServer myServer = new JavaHTTPServer(serverConnect.accept());
				
				if (verbose) {
					System.out.println("Connecton opened. (" + new Date() + ")");
				}
				
				// create dedicated thread to manage the client connection
				Thread thread = new Thread(myServer);
				thread.start();
			}
			
		} catch (IOException e) {
			System.err.println("Server Connection error : " + e.getMessage());
		}
	}

	@Override
	public void run() {
		// we manage our particular client connection
		BufferedReader in = null; PrintWriter out = null; BufferedOutputStream dataOut = null;
		String fileRequested = null;
		
		try {
			// we read characters from the client via input stream on the socket
			in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
			// we get character output stream to client (for headers)
			out = new PrintWriter(connect.getOutputStream());
			// get binary output stream to client (for requested data)
			dataOut = new BufferedOutputStream(connect.getOutputStream());
			
			// get first line of the request from the client
			String input = in.readLine();
			// we parse the request with a string tokenizer
			StringTokenizer parse = new StringTokenizer(input);
			String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
			// we get file requested
			fileRequested = parse.nextToken().toLowerCase();
			
			// we support only GET and HEAD methods, we check
			if (!method.equals("GET") && !method.equals("HEAD")) {
				if (verbose) {
					System.out.println("501 Not Implemented : " + method + " method.");
				}
				
				// we return the not supported file to the client
				File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
				int fileLength = (int) file.length();
				String contentMimeType = "text/html";
				//read content to return to client
				byte[] fileData = readFileData(file, fileLength);
					
				// we send HTTP Headers with data to client
				out.println("HTTP/1.1 501 Not Implemented");
				out.println("Server: Java HTTP Server from SSaurel : 1.0");
				out.println("Date: " + new Date());
				out.println("Content-type: " + contentMimeType);
				out.println("Content-length: " + fileLength);
				out.println(); // blank line between headers and content, very important !
				out.flush(); // flush character output stream buffer
				// file
				dataOut.write(fileData, 0, fileLength);
				dataOut.flush();
				
			} else {
				// GET or HEAD method
				if (fileRequested.endsWith("/")) {
					fileRequested += DEFAULT_FILE;
				}
				
				File file = new File(WEB_ROOT, fileRequested);
				int fileLength = (int) file.length();
				String content = getContentType(fileRequested);
				
				if (method.equals("GET")) { // GET method so we return content
					byte[] fileData = readFileData(file, fileLength);
					
					// send HTTP Headers
					out.println("HTTP/1.1 200 OK");
					out.println("Server: Java HTTP Server from SSaurel : 1.0");
					out.println("Date: " + new Date());
					out.println("Content-type: " + content);
					out.println("Content-length: " + fileLength);
					out.println(); // blank line between headers and content, very important !
					out.flush(); // flush character output stream buffer
					
					dataOut.write(fileData, 0, fileLength);
					dataOut.flush();
				}
				
				if (verbose) {
					System.out.println("File " + fileRequested + " of type " + content + " returned");
				}
				
			}
			
		} catch (FileNotFoundException fnfe) {
			try {
				fileNotFound(out, dataOut, fileRequested);
			} catch (IOException ioe) {
				System.err.println("Error with file not found exception : " + ioe.getMessage());
			}
			
		} catch (IOException ioe) {
			System.err.println("Server error : " + ioe);
		} finally {
			try {
				in.close();
				out.close();
				dataOut.close();
				connect.close(); // we close socket connection
			} catch (Exception e) {
				System.err.println("Error closing stream : " + e.getMessage());
			} 
			
			if (verbose) {
				System.out.println("Connection closed.\n");
			}
		}
		
		
	}
	
	private byte[] readFileData(File file, int fileLength) throws IOException {
		FileInputStream fileIn = null;
		byte[] fileData = new byte[fileLength];
		
		try {
			fileIn = new FileInputStream(file);
			fileIn.read(fileData);
		} finally {
			if (fileIn != null) 
				fileIn.close();
		}
		
		return fileData;
	}
	
	// return supported MIME Types
	private String getContentType(String fileRequested) {
		if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
			return "text/html";
		else
			return "text/plain";
	}
	
	private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
		File file = new File(WEB_ROOT, FILE_NOT_FOUND);
		int fileLength = (int) file.length();
		String content = "text/html";
		byte[] fileData = readFileData(file, fileLength);
		
		out.println("HTTP/1.1 404 File Not Found");
		out.println("Server: Java HTTP Server from SSaurel : 1.0");
		out.println("Date: " + new Date());
		out.println("Content-type: " + content);
		out.println("Content-length: " + fileLength);
		out.println(); // blank line between headers and content, very important !
		out.flush(); // flush character output stream buffer
		
		dataOut.write(fileData, 0, fileLength);
		dataOut.flush();
		
		if (verbose) {
			System.out.println("File " + fileRequested + " not found");
		}
	}
	
}

以上就是Java/Android 實現(xiàn)簡單的HTTP服務(wù)器的詳細內(nèi)容,更多關(guān)于Java/Android HTTP服務(wù)器的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Spring中的10種事務(wù)失效的常見場景

    Spring中的10種事務(wù)失效的常見場景

    這篇文章主要介紹了Spring中的10種事務(wù)失效的常見場景,Spring的聲明式事務(wù)功能更是提供了極其方便的事務(wù)配置方式,配合Spring Boot的自動配置,大多數(shù)Spring Boot項目只需要在方法上標記@Transactional注解,即可一鍵開啟方法的事務(wù)性配置,需要的朋友可以參考下
    2023-11-11
  • Java的枚舉,注解和反射(二)

    Java的枚舉,注解和反射(二)

    今天小編就為大家分享一篇關(guān)于Java枚舉,注解與反射原理說明,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2021-07-07
  • 一篇文章帶你搞定 springsecurity基于數(shù)據(jù)庫的認證(springsecurity整合mybatis)

    一篇文章帶你搞定 springsecurity基于數(shù)據(jù)庫的認證(springsecurity整合mybatis)

    這篇文章主要介紹了一篇文章帶你搞定 springsecurity基于數(shù)據(jù)庫的認證(springsecurity整合mybatis),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-10-10
  • Java掃描文件夾下所有文件名

    Java掃描文件夾下所有文件名

    這篇文章主要為大家詳細介紹了Java掃描文件夾下所有文件名,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • java dump文件怎么生成和分析-JMAP用法詳解

    java dump文件怎么生成和分析-JMAP用法詳解

    這篇文章主要介紹了java dump文件怎么生成和分析-JMAP用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • 搭建Springboot框架并添加JPA和Gradle組件的方法

    搭建Springboot框架并添加JPA和Gradle組件的方法

    這篇文章主要介紹了搭建Springboot框架并添加JPA和Gradle組件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • 一篇文章徹底弄懂Java中二叉樹

    一篇文章徹底弄懂Java中二叉樹

    二叉樹是有限個節(jié)點的集合,這個集合可以是空集,也可以是一個根節(jié)點和兩顆不相交的子二叉樹組成的集合,其中一顆樹叫根的左子樹,另一顆樹叫右子樹,這篇文章主要給大家介紹了一篇文章如何徹底弄懂Java中二叉樹的相關(guān)資料,需要的朋友可以參考下
    2022-01-01
  • Java設(shè)計模式之java命令模式詳解

    Java設(shè)計模式之java命令模式詳解

    這篇文章主要介紹了Java設(shè)計模式編程中命令模式的使用,在一些處理請求響應(yīng)的場合經(jīng)??梢杂玫矫钅J降木幊趟悸?需要的朋友可以參考下
    2021-09-09
  • java中struts 框架的實現(xiàn)

    java中struts 框架的實現(xiàn)

    本文給大家介紹的是java中struts 框架的實現(xiàn),有需要的小伙伴可以參考下。
    2015-06-06
  • Spring實現(xiàn)類私有方法的幾個問題(親測通用解決方案)

    Spring實現(xiàn)類私有方法的幾個問題(親測通用解決方案)

    現(xiàn)實的業(yè)務(wù)場景中,可能需要對Spring的實現(xiàn)類的私有方法進行測試。本文給大家分享Spring實現(xiàn)類私有方法面臨的幾個問題及解決方案,感興趣的朋友跟隨小編一起看看吧
    2021-06-06

最新評論