Import java.io.BufferedReader; Import java.io.IOException; Import the java.io.InputStreamReader; Import java.io.PrintWriter; Import the java.net.ServerSocket; Import the java.net.Socket; / ** * * @Description: // TODO simple HTTP server, in fact, accept the HTTP request and parse the request, * @author: sunfch * * @date: 2019/1/3 16:35 * @Param: * @return: * / public class the HttpServer { public static void main (String [] args) { the try { / * listening port number, as long as it can receive the 8888 * / the ServerSocket SS = new newThe ServerSocket (8888 ); the while ( to true ) { / * Examples of the client, a fixed routine, accepted by the target server, the client generates the corresponding instance * / the Socket Socket = ss.accept (); / * Get Client Input basic information flow, a request is over: request header, line breaks, the request body * / the BufferedReader BD = new new the BufferedReader ( new new the InputStreamReader (Socket.getInputStream ())); / ** * accept HTTP requests, and parse the data * / String RequestHeader; int contentLength = 0 ; the while ! ((RequestHeader = bd.readLine ()) =null &&! requestHeader.isEmpty ()) { System.out.println (RequestHeader); / ** * GET parameter obtained * / IF (requestHeader.startsWith ( "GET" )) { int the begin = requestHeader.indexOf ( "/" ); int End = requestHeader.indexOf ( "the HTTP /" ); String for condition Condition = requestHeader.substring (the begin, End); System.out.println ( "the gET parameter is:" + for condition Condition); } / ** * obtained POST 1. The content acquisition request parameter * length * / IF (requestHeader.startsWith("Content-Length")) { int begin = requestHeader.indexOf("Content-Lengh:") + "Content-Length:".length(); String postParamterLength = requestHeader.substring(begin+1).trim(); contentLength = Integer.parseInt(postParamterLength); System.out.println("POST参数长度是:" + Integer.parseInt(postParamterLength)); } } StringBuffer sb = new StringBuffer(); if (contentLength > 0) { for (int i = 0; i < contentLength; i++) { sb.append((char) bd.read()); } System.out.println("POST参数是:" + sb.toString()); } /* 发送回执 */ PrintWriter pw = new PrintWriter(socket.getOutputStream()); pw.println("HTTP/1.1 200 OK"); pw.println("Content-type:text/html"); pw.println(); pw.println("<HTML>"); pw.println("<TITLE>Index</TITLE>"); pw.println("<BODY>"); pw.println("<P>Welcome to J. David's webserver."); pw.println("<H1>CGI demo1"); pw.println("<FORM ACTION=\"color.cgi\" METHOD=\"POST\">"); pw.println("Enter a color: <INPUT TYPE=\"text\" NAME=\"color\">"); pw.println("<P>"); pw.println("Enter a number: <INPUT TYPE=\"text\" NAME=\"number\">"); pw.println("<INPUT TYPE=\"submit\">"); pw.println("</FORM>"); pw.println("</BODY>"); pw.println("</HTML>"); pw.flush(); socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }