Use socket in JAVA to implement HTTP requests

Source: Internet
Author: User

Java-based web server implementation mainly uses these two important classes: java.net. Socket and java.net. ServerSocket, and communicates through HTTP messages. An HTTP request consists of three parts: 1. method-Uniform Resource Identifier (URI)-Protocol/version 2. request Header 3. body content [plain] GET/HTTP/1.1 Host: 127.0.0.1: 8080 Connection: keep-alive Accept: text/html, application/xhtml + xml, application/xml; q = 0.9, image/webp, */*; q = 0.8 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) chrome/30.0.1599.101 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN, zh; q = 0.8 HTTP A response is similar to an HTTP request. An HTTP response consists of three parts: 1. method-Uniform Resource Identifier (URI)-Protocol/version 2. response Header 3. the following is an example of an HTTP Response: [plain] view plaincopyprint? HTTP/1.1 200 OK Server: IBM/4.0 Date: Sat, 6 Nov 2013 13:13:00 GMT Content-Type: text/html Last-Modified: Sat, 5 Jan 2013 13:13:12 GMT Content-Length: 112 socket-type socket is an endpoint of the network connection. A socket enables an application to read and write data from the network. Two applications deployed on two different computers can send and receive byte streams through connections. To send a message from your application to another application, you need to instruct the IP address and socket port of another application. The ServerSocket class represents a client Socket, that is, the Socket you construct whenever you want to connect to a remote server application. If a server program depends on the Socket class, it will not work. Your server must be on standby, because it is unknown when the client misses you to send a request. Server Socket is different from Socket. The role of server Socket is to wait for connection requests from the client. Once the server Socket receives a connection request, it creates a Socket instance to communicate with the client. The following is a simple HTTP request implementation: first create an HTTPSERVER service [java] public class HttpServer {public static final String WEB_ROOT = "d:/webroot "; private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; private boolean shutdown = false; public static void main (String [] args) {HttpServer server = new HttpServer (); server. await ();} public void await () {ServerSocket serverSocket = null; int port = 8080; try {serverSock Et = new ServerSocket (port, 1, InetAddress. getByName ("127.0.0.1");} catch (UnknownHostException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace (); System. exit (1);} // Loop waiting for a request while (! Shutdown) {Socket socket = null; InputStream input = null; OutputStream output = null; try {socket = serverSocket. accept (); input = socket. getInputStream (); output = socket. getOutputStream (); // create Request object and parse Request request = new Request (input); request. parse (); // create Response object Response response = new Response (output); response. setRequest (request); response. sendStatic Resource (); // Close the socket; socket. close (); // check if the revious URI is a shutdown command shutdown = request. getUri (). equals (SHUTDOWN_COMMAND);} catch (IOException e) {e. printStackTrace (); continue ;}}} the corresponding service must Request [java] public class Request {private InputStream input; private String uri; public Request (InputStream input) {this. input = input;} public void parse () {// Read a set Characters from the socket StringBuffer request = new StringBuffer (2018); int I; byte [] buffer = new byte [2048]; try {I = input. read (buffer);} catch (IOException e) {e. printStackTrace (); I =-1 ;}for (int j = 0; j <I; j ++) {request. append (char) buffer [j]);} System. out. println ("----------------- request ----------------"); System. out. print (request. toString (); uri = parseUri (request. toString ();} Private String parseUri (String requestString) {int index1, index2; index1 = requestString. indexOf (''); if (index1! =-1) {index2 = requestString. indexOf ('', index1 + 1); return requestString. substring (index1 + 1, index2);} return null;} public String getUri () {return uri ;}} the corresponding Request must have a Response [java] public class Response {private static final int BUFFER_SIZE = 1024; private request Request; private OutputStream output; public Response (OutputStream output) {this. output = output;} public void setRequest (Request re Quest) {this. request = request;} public void sendStaticResource () throws IOException {byte [] bytes = new byte [BUFFER_SIZE]; FileInputStream FD = null; boolean errorFlag = true; if (request. getUri ()! = Null) {File file = new File (HttpServer. WEB_ROOT, request. getUri (); if (file. exists () {fiis = new FileInputStream (file); int ch = fiis. read (bytes, 0, BUFFER_SIZE); while (ch! =-1) {output. write (bytes, 0, ch); ch = FCM. read (bytes, 0, BUFFER_SIZE);} errorFlag = false;} if (errorFlag) {// file not found String errorMessage = "HTTP/1.1 404 File NOT Fount \ r \ n" + "Content-Type: text/html \ r \ n "+" Content-Length: 23 \ r \ n "+" \ r \ n "+"

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.