Java Http server demo

Source: Internet
Author: User

Java Http server demo

Import java. io. *; import java.net. *;/*** MyHttpServer implements a simple HTTP server that can obtain the content submitted by the user * and give the user a response * due to the time relationship, the processing of the http header is not standard **/public class MyHttpServer {// server root directory, post.html, upload.html are all placed in this location public static String WEB_ROOT = "c:/root "; // port private int port; // The url private String requestPath of the file requested by the user; // delimiter for post submission in mltipart/form-data mode, private String boundary = null; // The length of the body of the post request is private int. ContentLength = 0; public MyHttpServer (String root, int port) {WEB_ROOT = root; this. port = port; requestPath = null;} // process the GET request private void doGet (DataInputStream reader, OutputStream out) throws Exception {if (new File (WEB_ROOT + this. requestPath ). exists () {// find the file requested by the user under the root directory of the server and send it back to the browser InputStream fileIn = new FileInputStream (WEB_ROOT + this. requestPath); byte [] buf = new byte [fileIn. availabl E ()]; fileIn. read (buf); out. write (buf); out. close (); fileIn. close (); reader. close (); System. out. println ("request complete. ") ;}} // process the post request private void doPost (DataInputStream reader, OutputStream out) throws Exception {String line = reader. readLine (); while (line! = Null) {System. out. println (line); line = reader. readLine (); if ("". equals (line) {break;} else if (line. indexOf ("Content-Length ")! =-1) {this. contentLength = Integer. parseInt (line. substring (line. indexOf ("Content-Length") + 16);} // indicates that you want to upload an attachment and jump to the doMultiPart method. Else if (line. indexOf ("multipart/form-data ")! =-1) {// delimiter of multiltipart this. boundary = line. substring (line. indexOf ("boundary") + 9); this. doMultiPart (reader, out); return ;}// continue to read data submitted by normal post (no attachment) System. out. println ("begin reading posted data ...... "); String dataLine = null; // The post Data body sent by the user. byte [] buf ={}; int size = 0; if (this. contentLength! = 0) {buf = new byte [this. contentLength]; while (size
 
  
"; System. out. println (body); out. write (response. getBytes (); out. write (body. getBytes (); out. flush (); reader. close (); out. close (); System. out. println ("request complete. ");} // process the attachment private void doMultiPart (DataInputStream reader, OutputStream out) throws Exception {System. out. println ("doMultiPart ...... "); String line = reader. readLine (); while (line! = Null) {System. out. println (line); line = reader. readLine (); if ("". equals (line) {break;} else if (line. indexOf ("Content-Length ")! =-1) {this. contentLength = Integer. parseInt (line. substring (line. indexOf ("Content-Length") + 16); System. out. println ("contentLength:" + this. contentLength);} else if (line. indexOf ("boundary ")! =-1) {// obtain the multipart separator this. boundary = line. substring (line. indexOf ("boundary") + 9);} System. out. println ("begin get data ...... ");/* The comment below is the full text of a request with attachments sent by a browser. All Chinese characters are descriptive texts *****
  
   
...... Cache-Control: no-cache
   <这里有一个空行,表明接下来的内容都是要提交的正文>
    
----------------------------- 7d925132131f6
    <这是multipart分隔符>
     
Content-Disposition: form-data; name = "myfile"; filename = "mywork.doc" Content-Type: text/plain
     <附件正文>
      
........................................ ........................................ ......... ----------------------------- 7d925132131f6
      <这是multipart分隔符>
        Content-Disposition: form-data; name = "myname"
       <其他字段或附件> 
        <这里有一个空行> 
         <其他字段或附件的内容>
           ----------------------------- 7d925132131f6 --
          <这是multipart分隔符,最后一个分隔符多两个->
            **************************************** * ********************** // The comment above is of the multipart type with attachments. POST full-text model, * To remove the attachment, you must find the start position and end position of the attachment body. **/if (this. contentLength! = 0) {// read all submitted bodies, including attachments and other fields to buf. byte [] buf = new byte [this. contentLength]; int totalRead = 0; int size = 0; while (totalRead <this. contentLength) {size = reader. read (buf, totalRead, this. contentLength-totalRead); totalRead + = size;} // construct a String using buf. You can use the String to conveniently calculate the position of the attachment, String dataString = new String (buf, 0, totalRead); System. out. println ("the data user posted:/n" + dataString); int pos = dat AString. indexOf (boundary); // The Position of the first attachment is pos = dataString. indexOf ("/n", pos) + 1; pos = dataString. indexOf ("/n", pos) + 1; pos = dataString. indexOf ("/n", pos) + 1; pos = dataString. indexOf ("/n", pos) + 1; // start position of the attachment int start = dataString. substring (0, pos ). getBytes (). length; pos = dataString. indexOf (boundary, pos)-4; // The end position of the attachment. int end = dataString. substring (0, pos ). getBytes (). length; // locate fil Ename int fileNameBegin = dataString. indexOf ("filename") + 10; int fileNameEnd = dataString. indexOf ("/n", fileNameBegin); String fileName = dataString. substring (fileNameBegin, fileNameEnd);/*** sometimes the uploaded file displays the complete file name path, such as c:/my file/somedir/project.doc *. sometimes only the file name is displayed, such as myphoto.jpg. * therefore, you need to make a judgment. */If (fileName. lastIndexOf ("//")! =-1) {fileName = fileName. substring (fileName. lastIndexOf ("//") + 1);} fileName = fileName. substring (0, fileName. length ()-2); OutputStream fileOut = new FileOutputStream ("c: //" + fileName); fileOut. write (buf, start, end-start); fileOut. close (); fileOut. close ();} String response = ""; response + = "HTTP/1.1 200 OK/n"; response + = "Server: Sunpache 1.0/n "; response + = "Content-Type: text/html/n"; response + = "Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT/n "; response + = "Accept-ranges: bytes"; response + = "/n"; out. write ("
           Test server
           

Post is OK

". GetBytes (); out. flush (); reader. close (); System. out. println ("request complete. ");} public void service () throws Exception {ServerSocket serverSocket = new ServerSocket (this. port); System. out. println ("server is OK. "); // enable serverSocket to wait for user requests to arrive, then process the request according to the request type. // here I only process GET and POST. // POST has the ability to parse a single attachment. while (true) {Socket socket = serverSocket. accept (); System. out. println (socket. getInetAddress (); System. out. println ("new request coming. "); DataInputStream reader = new DataInputStream (socket. getInputStream (); String line = reader. readLine (); String method = line. substring (0, 4 ). trim (); OutputStream out = socket. getOutputStream (); this. requestPath = line. split ("") [1]; System. out. println (method); if ("GET ". equalsIgnoreCase (method) {System. out. println ("do get ...... "); this. doGet (reader, out);} else if ("POST ". equalsIgnoreCase (method) {System. out. println ("do post ...... "); this. doPost (reader, out);} socket. close (); System. out. println ("socket closed. ") ;}} public static void main (String args []) throws Exception {MyHttpServer server = new MyHttpServer (" c:/root ", 8080); server. service ();}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.