📄 httpserver.java
字号:
package org.placelab.proxy;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.URL;import java.util.Hashtable;import org.placelab.util.StringUtil;public abstract class HTTPServer extends SocketServer { public HTTPServer (int port, int threadCount, String label) { super(port, threadCount, label); } private static String readLine (byte[] request) throws IOException { for (int i=0;i<request.length;i++) { int b = request[i] & 0xff; if (b == '\n') return new String(request, 0, i); } return null; } public void serviceSocket (Socket s) { try { InputStream in = s.getInputStream(); byte[] request = getByteArray(in); String firstLine = readLine(request); if (firstLine == null) return; String[] parts = StringUtil.split(firstLine, ' ', 3); String method = parts[0]; String url = parts[1]; Hashtable headers = getHeaders(new ByteArrayInputStream(request)); String host = (String) headers.get("Host"); if (url.indexOf(host) == -1 && (url.indexOf("http") != 0)) url = "http://" + host + ((url.charAt(0) == '/') ? "" : "/") + url; HTTPRequest httpRequest = new HTTPRequest(new URL(url), method, headers); HTTPResponse httpResponse = serviceRequest(httpRequest); OutputStream out = s.getOutputStream(); out.write(httpResponse.getBytes()); out.write((byte) 0); }catch (IOException e) { e.printStackTrace(); } } public byte[] getByteArray (InputStream in) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); boolean block = true; while (block) { int b; try { b = in.read(); buffer.write(b); } catch (IOException e) { block = false; } if (in.available() == 0) block = false; } return buffer.toByteArray(); } public static Hashtable getHeaders(InputStream in) throws IOException { Hashtable headers = new Hashtable(); StringBuffer buffer = new StringBuffer(); for (;;) { int b = in.read(); if ( (b == '\n') || (b == '\r') || (b == -1) ) { String line = buffer.toString().trim(); buffer = new StringBuffer(); if (line.length() > 0) { String[] pair = StringUtil.split(line, ':', 2); if (pair.length != 2) continue; if (pair[1].charAt(0) == ' ') pair[1] = pair[1].substring(1); headers.put(pair[0], pair[1]); } if (b==-1) break; } else { buffer.append((char) b); } } return headers; } public abstract HTTPResponse serviceRequest (HTTPRequest request);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -