亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Java/Android 實現簡單的HTTP服務器

瀏覽:8日期:2022-08-22 10:55:24

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

網上查詢了一下,找到可用的代碼如下:

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 Threadpublic 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 connectionstatic final int PORT = 8080;// verbose modestatic final boolean verbose = true;// Client Connection via Socket Classprivate 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 executionwhile (true) {JavaHTTPServer myServer = new JavaHTTPServer(serverConnect.accept());if (verbose) {System.out.println('Connecton opened. (' + new Date() + ')');}// create dedicated thread to manage the client connectionThread thread = new Thread(myServer);thread.start();}} catch (IOException e) {System.err.println('Server Connection error : ' + e.getMessage());}}@Overridepublic void run() {// we manage our particular client connectionBufferedReader in = null; PrintWriter out = null; BufferedOutputStream dataOut = null;String fileRequested = null;try {// we read characters from the client via input stream on the socketin = 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 clientString input = in.readLine();// we parse the request with a string tokenizerStringTokenizer parse = new StringTokenizer(input);String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client// we get file requestedfileRequested = parse.nextToken().toLowerCase();// we support only GET and HEAD methods, we checkif (!method.equals('GET') && !method.equals('HEAD')) {if (verbose) {System.out.println('501 Not Implemented : ' + method + ' method.');}// we return the not supported file to the clientFile file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);int fileLength = (int) file.length();String contentMimeType = 'text/html';//read content to return to clientbyte[] fileData = readFileData(file, fileLength);// we send HTTP Headers with data to clientout.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// filedataOut.write(fileData, 0, fileLength);dataOut.flush();} else {// GET or HEAD methodif (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 contentbyte[] fileData = readFileData(file, fileLength);// send HTTP Headersout.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 bufferdataOut.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 Typesprivate String getContentType(String fileRequested) {if (fileRequested.endsWith('.htm') || fileRequested.endsWith('.html'))return 'text/html';elsereturn '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 bufferdataOut.write(fileData, 0, fileLength);dataOut.flush();if (verbose) {System.out.println('File ' + fileRequested + ' not found');}}}

以上就是Java/Android 實現簡單的HTTP服務器的詳細內容,更多關于Java/Android HTTP服務器的資料請關注好吧啦網其它相關文章!

標簽: Java
相關文章:
主站蜘蛛池模板: 日本高清不卡二区 | 黄页网址免费 | 一级黄色大毛片 | 国产精品午夜激爽毛片 | 宅女深夜福利视频在线 | 国产高清尿小便嘘嘘视频 | 亚洲a区视频 | 女人午夜啪啪性刺激免费看 | 97一级毛片全部免费播放 | 欧美特黄高清免费观看的 | 男女叼嘿视频大全免费看 | 毛片在线播放a | 九九九九在线精品免费视频 | 午夜日b视频| 香蕉久久网站 | 中文字幕在线播放第一页 | 久久亚洲综合中文字幕 | 91综合视频 | 在线看黄网址 | 亚洲色图综合区 | 日本多人激情免费视频 | 国产三级精品三级在线专区91 | 国产ar高清视频+视频 | xxx国产 | 天天爱天天做色综合 | 国产一区二区免费视频 | 99国产精品热久久久久久夜夜嗨 | 网友偷自拍原创区 | 国产肉丝在线 | 最新国语露脸精品国产 | 欧美成人看片一区二区三区 | 国产成人精品日本亚洲语音 | 欧美日韩国产亚洲一区二区三区 | 国产精品吹潮香蕉在线观看 | 国产一级性生活片 | 中文字幕三区 | 免费一区二区三区四区五区 | 91精品国产自产91精品 | 国产一级特黄生活片 | 毛片网站在线播放 | 狠狠色噜噜狠狠狠狠888奇米 |