Server implementation handles GET and post

Source: Internet
Author: User

ImportJava.io.File;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.net.URLDecoder;ImportJava.util.regex.Matcher;ImportJava.util.regex.Pattern; Public classHttpserver { Public Static voidDoget (String message,outputstream op)throwsioexception{//Display MessagesSystem.out.println (message); Pattern P= Pattern.compile ("/?a= (. +) HTTP")); Matcher page=p.matcher (message); String result= "";  while(Page.find ()) {//System.out.println (Page.group (1));result = Page.group (1); } result= Urldecoder.decode (Result, "GBK"); //The key is Utf-8 .OutputStreamWriter OSW =NewOutputStreamWriter (OP, "Utf-8")); Osw.write ("http/1.1 ok\r\n"); Osw.write ("Server:apache-coyote/1.1\r\n"); //osw.write ("SET-COOKIE:JSESSIONID=03493794995CE31A0F131787B6C6CBB2; path=/; Httponly\r\n ");Osw.write ("content-type:text/html;charset=utf-8\r\n"); Osw.write ("Transfer-encoding:chunked\r\n"); Osw.write ("Date:tue, 02:48:27 gmt\r\n"); Osw.write ("\ r \ n"); Osw.write ("C9\r\n"); Osw.write ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" >\r\n "); Osw.write ("); Osw.write ("); Osw.write ("<body>\r\n"); //Osw.write ("This is MyServ, using the GET method\r\n");Osw.write ("You have entered:" +result); Osw.write ("</body>\r\n"); Osw.write ("); Osw.write ("\ r \ n"); //Osw.write ("0");Osw.write ("\ r \ n"); Osw.write ("\ r \ n");        Osw.flush ();        Osw.close ();        Op.flush ();                                   Op.close (); }         Public Static voidDoPost (String message,outputstream op,byte[] buf)throwsioexception{//Display MessagesSystem.out.println (message); //Collect Data        NewThread (NewRunnable () {@Override Public voidrun () {Pattern P= Pattern.compile ("Filename=\" (. +) \ ""); Matcher page=p.matcher (message); String filename= "";  while(Page.find ()) {System.out.println (Page.group (1)); FileName= Page.group (1); } File File=NewFile ("c:\\users\\binbin\\desktop\\ Network job \\ReciveFile" + "\ \" +filename); //if (!file.exists ()) {                                        Try{file.createnewfile (); FileOutputStream FOP=Newfileoutputstream (file); Fop.write (BUF,556,20);                                                                                            Fop.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }                                    //}}}). Start (); //The key is Utf-8 .OutputStreamWriter OSW =NewOutputStreamWriter (OP, "Utf-8")); Osw.write ("http/1.1 ok\r\n"); Osw.write ("Server:apache-coyote/1.1\r\n"); //osw.write ("SET-COOKIE:JSESSIONID=03493794995CE31A0F131787B6C6CBB2; path=/; Httponly\r\n ");Osw.write ("content-type:text/html;charset=utf-8\r\n"); Osw.write ("Transfer-encoding:chunked\r\n"); Osw.write ("Date:tue, 02:48:27 gmt\r\n"); Osw.write ("\ r \ n"); Osw.write ("C9\r\n"); Osw.write ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" >\r\n "); Osw.write ("); Osw.write ("); Osw.write ("<body>\r\n"); Osw.write ("Post method:upload ok!\r\n"); Osw.write ("</body>\r\n"); Osw.write ("); Osw.write ("\ r \ n"); Osw.write ("\ r \ n"); Osw.write ("\ r \ n");        Osw.flush ();        Osw.close ();        Op.flush ();                                    Op.close (); }                 Public Static voidMain (string[] args)throwsIOException, interruptedexception {//Server listener Port numberServerSocket ServerSocket =NewServerSocket (8099); //The dead Loop server has been running         while(true){              //wait for the request to be received, this is a blocking method that will continue to execute when the request arrivesSocket socket =serversocket.accept (); //GET request Content InputStreamInputStream is =Socket.getinputstream (); Thread.Sleep (500); //return message with OutputStreamOutputStream out =Socket.getoutputstream (); File File=NewFile ("GetMetho.txt"); FileOutputStream FOP=Newfileoutputstream (file); //Get Messages        intLen = 0; byte[] buf =New byte[1024]; String message= "";  while((Len=is.read (BUF))!=-1) {Message+=NewString (buf,0, Len); /*if (message.contains ("Favicon.ico") | |            Message.contains ("google.com:443")) break; */Fop.write (buf,0, Len);  Break;                } fop.close (); //System.out.println (message);                        if(Message.contains ("Favicon.ico") | | Message.contains ("google.com:443"))            Continue; //if it is a post        Else if(Message.contains ("POST") {httpserver.dopost (MESSAGE,OUT,BUF); }                //if it is a get        Else if(Message.contains ("GET")){            //System.out.println (message);Httpserver.doget (message,out); }                Else;                                                   Is.close (); }//End While                                    }  }

Get HTML:

<HTML><Body><formAction= "http://localhost:8099"Method= "Get"><inputname= "a"type= "text"value= "Hello" /><inputname=""type= "Submit"value= "Submit" /></form></Body></HTML>

HTML for post:

<formAction= "http://localhost:8099"enctype= "Multipart/form-data"Method= "POST">      <INPUTNAME= "Userfile1"TYPE= "File">     <inputtype= "Submit"value= "Submit"/>  </form>  

Post is actually water, because the book inside get uploaded file content that piece of code too long, do not want to write. Just count the number of words in front of the message directly from the back to start reading.

Server implementation handles GET and post

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.