an HTTP
HTTP Request
An HTTP request typically consists of the following three sections:
1 request methods, such as Get,post
2 Request Header
3 Entities
ahttp request is as follows:
Get /index.jsp http/1.1
host:localhost:8080
user-agent:mozilla/5.0 (Windows NT 5.1; rv:15.0) gecko/20100101 firefox/15.0
accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-language:zh-cn,zh;q=0.8,en-us ; q=0.5,en;q=0.3
Accept-encoding:gzip, deflate
Connection:keep-alive
Pay attention to the red part of the URL, which we will intercept later.
http response
similar to HTTP request, HTTP response also includes three parts
1 protocol-Status code-Description
2 response Header
3 response entity segment
Two socket class The
socket is a breakpoint on a network connection. Sockets enable applications to read data from the network and write data to the network. Applications on different computers can send or receive byte streams through sockets. The socket class is provided in Java for this function, and the input and output streams in the network can be obtained through getInputStream and Getoutputstream.
However, the socket class is still not able to implement our ability to build a server application, because the server must always be on standby, so Java has a ServerSocket class to handle requests waiting from the client, When ServerSocket receives a request from the client, it creates an instance to handle communication with the client.
Implementation of the three-server application
First, we will build a class requst that encapsulates the request information, a class that responds to the request response, and a main program Httpserver to handle requests from the client.
PackageCom.lwq;Importjava.io.IOException;ImportJava.io.InputStream;/** * @authorJoker* Class Description * Convert request information from browser to character and intercept URL*/ Public classRequest {//input Stream PrivateInputStream input; //intercept URLs, such as http://localhost:8080/index.html, intercept part of/index.html PrivateString URI; PublicRequest (InputStream inputstream) { This. Input =InputStream; } PublicInputStream GetInput () {returninput; } Public voidsetinput (InputStream input) { This. Input =input; } PublicString GetURI () {returnURI; } Public voidSeturi (String uri) { This. Uri =URI; } //reading character information from a socket Public voidParse () {StringBuffer request=NewStringBuffer (2048); inti = 0; byte[] buffer =New byte[2048]; Try{i=input.read (buffer); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); I=-1; } for(intj = 0;j<i;j++) {request.append (Char) (Buffer[j])); } System.out.println (Request.tostring ()); URI=Parseuri (request.tostring ()); } //URL to intercept request Privatestring Parseuri (String requeststring) {intindex1 = 0; intIndex2 = 0; Index1= Requeststring.indexof (' '); if(Index1!=-1) {Index2= Requeststring.indexof ("', index1+1); if(index2>index1) { returnRequeststring.substring (index1+1, INDEX2); } } return NULL; } }
The following is the class response that encapsulates the response request:
PackageCom.lwq;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;/** * @authorJoker *@versioncreation Time: Sep 5, 9:59:53 PM * Class description return results based on appropriate information*/ Public classResponse {Private Static Final intBuffer_size = 1024; Request request; OutputStream output; PublicResponse (OutputStream output) { This. Output =output; } Public voidSendstaticresource ()throwsioexception{byte[] bytes =New byte[Buffer_size]; FileInputStream FIS=NULL; File File=NewFile (Httpserver.web_root,request.geturi ()); if(File.exists ()) {Try{FIS=Newfileinputstream (file); intch = fis.read (bytes,0, buffer_size); while(ch! =-1) {output.write (bytes,0, CH); CH= Fis.read (bytes,0, buffer_size); } } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }Catch(IOException e) {e.printstacktrace (); }finally{ if(FIS! =NULL) {fis.close (); } } }Else{ //the file could not be foundString errormessage = "http/1.1 404 File Not found\r\n" + "content-type:text/html\r\n" + "content-length:23\r\n" + "\ r \ n" +"File not Found";Try{output.write (errormessage.getbytes ()); Output.flush (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } PublicRequest getrequest () {returnrequest; } Public voidsetrequest (Request request) { This. Request =request; } PublicOutputStream getoutput () {returnoutput; } Public voidsetoutput (OutputStream output) { This. Output =output; } Public Static intgetbuffer_size () {returnbuffer_size; } }
Next is the main program,
PackageCom.lwq;ImportJava.io.File;ImportJava.io.InputStream;ImportJava.io.OutputStream;Importjava.net.InetAddress;ImportJava.net.ServerSocket;ImportJava.net.Socket;/** * @authorJoker* Class Description*/ Public classHttpserver {/** * @paramargs*/ //Web_root is the root directory of the server Public Static FinalString web_root = System.getproperty ("User.dir") +file.separator+ "Webroot"; //commands that are closed Private Static FinalString shutdown_command= "/shutdown"; Public Static voidMain (string[] args) {//TODO auto-generated Method StubHttpserver Server =NewHttpserver (); Server.await (); } Public voidawait () {ServerSocket ServerSocket=NULL; intPort = 8080; Try{ServerSocket=NewServerSocket (Port,1,inetaddress.getbyname ("127.0.0.1")); while(true) { Try{Socket Socket=NULL; InputStream input=NULL; OutputStream Output=NULL; Socket=serversocket.accept (); Input=Socket.getinputstream (); Output=Socket.getoutputstream (); //Encapsulating request RequestsRequest Request =NewRequest (input); Request.parse (); //Encapsulating Response ObjectsResponse Response =NewResponse (output); Response.setrequest (Request); Response.sendstaticresource (); Socket.close (); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); Continue; } } } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }
Run Httpserver, http://localhost:8080/index.jsp in the browser, you can see the results of the server response.
Java Server Simple implementation