Analog interface request to Web server

Source: Internet
Author: User
Tags ftp connection

Client

 Packagecom.lsw.client;ImportJava.io.*;Importjava.net.*;ImportJava.util.*; Public classhttpclinet { Public Static voidMain (string[] args) {//to determine the URI of an HTTP requestString uri = "index.html"; if(Args.length!=0) URI= Args[0]; //access Httpserver by GET requestDoget ("localhost", 8080, URI); }    //access Httpserver by GET request     Public Static voidDoget (String host,intport,string URI) {Socket Socket=NULL; Try{            //establishing an FTP connection with HttpserverSocket =NewSocket (Host,port); }        Catch(Exception e) {e.printstacktrace (); }                Try{            //Create an HTTP request//the first line of the HTTP requestStringBuffer SB =NewStringBuffer ("GET" +uri+ "http/1.1\r\n"); //HTTP request HeaderSb.append ("Accept: */*\r\n"); Sb.append ("Accept-language:zh-cn\r\n"); Sb.append ("Accept-encoding:gzip, deflate\r\n"); Sb.append ("User-agent:httpclient\r\n"); Sb.append ("Host:localhost:8080\r\n"); Sb.append ("Connection:keep-alive\r\n\r\n"); //Send HTTP requestOutputStream socketout = Socket.getoutputstream ();//get the output streamSocketout.write (Sb.tostring (). GetBytes ()); //Sleep 2 seconds, wait for response resultsThread.Sleep (2000); //Receive Response ResultsInputStream socketin = Socket.getinputstream ();//Get input stream            intSize =socketin.available (); byte[] buffer =New byte[size];            Socketin.read (buffer); String Request=NewString (buffer);        SYSTEM.OUT.PRINTLN (Request); }        Catch(Exception e) {e.printstacktrace (); }        finally{            Try{socket.close (); }Catch(Exception e) {e.printstacktrace (); }        }    }}

Service side

 PackageCom.lsw.server;ImportJava.io.*;Importjava.net.*; Public classHttpserver { Public Static voidMain (string[] args) {intPort;                ServerSocket ServerSocket; Try{Port= Integer.parseint (args[0]); System.out.println ("The default port is:" +port); }        Catch(Exception e) {System.out.println ("Default port 8080"); Port= 8080; }                Try{            //creating a listening portServerSocket =NewServerSocket (port); System.out.println ("Server is listening on port:" +Serversocket.getlocalport ());  while(true){                Try{                    //waiting for a customer's link request                    FinalSocket socket =serversocket.accept (); System.out.println ("A new TCP connection was established with the customer, the address of the customer is:" +socket.getinetaddress ()+ "Port is:" +Socket.getport ()); //responding to customer requestsService (socket); }                Catch(Exception e) {e.printstacktrace (); }            }                       }        Catch(Exception e) {e.printstacktrace (); }    }         Public Static voidService (socket socket)throwsexception{//read HTTP request InformationInputStream socketin = Socket.getinputstream ();//Get input stream//sleeps 500 milliseconds, waits for an HTTP requestThread.Sleep (500); intSize =socketin.available (); byte[] buffer =New byte[size];        Socketin.read (buffer); String Request=NewString (buffer); //Print HTTP request dataSYSTEM.OUT.PRINTLN ("The data requested by the client is:" +request); //Parsing HTTP requests//get HTTP request first lineString firstlineofrequest = request.substring (0,request.indexof ("\ r \ n")); System.out.println ("Firstlineofrequest=" +firstlineofrequest); //parsing the first line of an HTTP requeststring[] Parts = Firstlineofrequest.split (""); //URI that resolves HTTP requestsString uri = parts[1]; System.out.println ("Parsing HTTP requests for this uri=" +URI); System.out.println ("VALUE =" + uri.substring (0, 1). toString ()); String Flag= uri.substring (0, 1). toString (); if(Flag.equals ("/") {System.out.println ("This request is a request initiated from the browser"); URI= uri.substring (1). toString (); } System.out.println ("Parsing HTTP requests for this uri=" +URI); //determines the type of HTTP response body, simplified processing hereString ContentType; if(Uri.indexof ("html")! =-1 | | uri.indexof ("htm")! =-1) ContentType= "Text/html"; Else if(Uri.indexof ("jpg")! =-1 | | uri.indexof ("JPEG")! =-1) ContentType= "Image/jpeg"; Else if(Uri.indexof ("gif")! =-1) ContentType= "Image/gif"; ElseContentType= "Application/octet-stream";//byte stream type//Creating HTTP Response Results//Create the first line of the HTTP responseString responsefirstline = "http/1.1 ok\r\n"; //HTTP response HeaderString Responseheader = "Content-type:" +contenttype + "\r\n\r\n"; //gets the input stream that reads the response body data        /*InputStream in = HTTPServer.class.getResourceAsStream (URI); That's what the book says.*/InputStream in= Httpserver.class. getClassLoader (). getResourceAsStream (URI); //Send HTTP response resultsOutputStream socketout = Socket.getoutputstream ();//get the output stream//the first line of the HTTP response is sentSocketout.write (Responsefirstline.getbytes ()); //headers that send HTTP responsesSocketout.write (Responseheader.getbytes ()); System.out.println ("Message Hair delivery Complete"); System.out.println ("Start sending the body of the HTTP response"); //send the body of the HTTP response        intLen = 0; Buffer=New byte[1024]; Try {             while((len=in.read (buffer))! =-1) socketout.write (buffer,0, Len); } Catch(Exception e) {e.printstacktrace (); } System.out.println ("Complete the body of the sending HTTP response"); //sleep 1 seconds, waiting for customers to receive HTTP response resultsThread.Sleep (1000); //To close a TCP connectionSocket.close (); }}
<! DOCTYPE html>    <br >  </body>

Analog interface request to Web server

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.