Write a Web server and framework with your bare hands in Java < chapter II: request and Response>

Source: Internet
Author: User
Tags locale response code rewind rfc822

Use Java to write a Web server and frame with your bare hands < chapter I: NiO articles >

Then, speaking of accepting the request, the next step is to parse the request building the requestor object and create the response object to return.

Please note that there are many flaws. The process of processing a lot of servers in production is omitted, for informational purposes only. The content of the article may be modified in a continuous and complete context.

First

Project Address: Https://github.com/csdbianhua/Telemarketer

First look at how to parse the request

Parse requests Build Request object

This part of the corresponding code here, can be viewed in contrast

A GET request for an HTTP is probably shown below.

get/http/1.1

host:123.45.67.89

Connection:keep-alive

Cache-control:max-age=0

...

A POST request for an HTTP is probably as follows

Post/post http/1.1

host:123.45.67.89

Connection:keep-alive

Cache-control:max-age=0

...

\ r \ n

One=23&two=123

The request line begins with a method symbol, separated by a space, followed by the requested URI and version of the Protocol. The next step is a series of head fields, and we'll first extract them and save them to the request object, regardless of the function. There is a \ r \ n At the end of each line, and a separate \ R or \ n character is not allowed except as the end of the \ r \ n. The Post method has a message body, separated from the HTTP header by a \ r \ n.

Then we should have a few members of the request object.

1 Private String Path; 2 Private String method; 3 Private Map<string, string> head; 4 Private Map<string, string> requestparameters; 5 Private byte [] messagebody;

Where path is the URI of the request, method is the request, Head is the header field, Requestparameter is the request parameter (such as 123.45.67.89/?one=23&two=123, the parameter is one=23 and two= 123. or post table dropdowns), because there may be binary data in the MessageBody, the unified first with byte[]

OK, now it's time to start chewing on the bytebuffer that NiO reads.

First step: beheading an HTTP request

First we have to separate the head and body.

Since reading is Bytebuffer, then the first thing to read is to adjust the position of position. Otherwise, it is completely out of data to continue reading down the written position. Then this

If (buffer.position ()! = 0) {buffer.flip ();}

Flip () Does not need to say more about the source code to do so a few things limit = position; position = 0; Mark =-1;

Next read it's byte array

1     int remaining = buffer.remaining (); 2     byte New byte [remaining]; 3     Buffer.get (bytes);

And then we start to loop around and find two \ r \ n Simultaneous occurrences, and that's where we're going to cut the neck.

1      for(inti = 0; I < remaining; i++) {2         if(Bytes[i] = = ' \ r ' && bytes[i + 1] = = ' \ n ') {3Position =i;4i + = 2;5         }6         if(i + 1 < remaining && bytes[i] = = ' \ r ' && bytes[i + 1] = = ' \ n ') {7              Break;8         }9     }Ten Buffer.rewind (); One     byte[] head =New byte[position]; ABuffer.get (Head, 0, position); -     byte[] BODY =NULL; -     if(Remaining-position > 4) { theBuffer.position (position + 4); -BODY =New byte[Remaining-position-4]; -Buffer.get (body, 0, remaining-position-4); -}

Also remember to re-read the words after get is finished to rewind() return position to zero. Note that this sentence buffer.position (position + 4) is read from the beginning of buffer.position. And buffer.position at this time has reached the end of the head, want to read body as long as let position forward four bit.

By the end of this, the head of a byte array byte[] heads and the body of the byte array byte[] head.

The next step is the real critical parsing.

Step two: Dissect two bytes

The head is basically the UTF-8 code, the direct BR reads on the line.

BufferedReader reader = new bufferedreader ( new StringReader (new String (head, "UTF-8")) );

Read the first line separated by a space, the first is the request method, the second is a URI. Note To use Urldecoder.decode (lineone[1], "utf-8");   To decode the URI because it might include escape characters such as%20.

Next read each line String[]  keyValue = line.split(":");  and then remove the space added to Headmap headmap.put (Keyvalue[0].trim (), Keyvalue[1].trim ()); The head is finished.

Then is the parameter, first get the parameter of GET, then get the parameter of the post form. After the string (one=23&two=123) is obtained, it is parsed using this method.

1 void parseparameters (string s, map<string, string> requestparameters) {2     string [] paras = S.split ("&"); 3      for (String para:paras) {4         string[] split = para.split ("="); 5         Requestparameters.put (split[0], split[1]); 6     }7 }

Like get.

1 string[] Pathpart = path.split ("\ \") ); 2 Path = pathpart[0]; 3 if (Pathpart.length = = 2) {4     parseparameters (pathpart[1], requestparameters); 5 }

How to judge is not the post form, can see Content-type is not application/x-www-form-urlencoded

Headmap.containskey ("Content-type") && headmap.get ("Content-type"). Contains ("application/ X-www-form-urlencoded ")

So the request came out.

Create Response Build Response object

This part of the corresponding code here, can be viewed in contrast

Let's look at a simplified HTTP response

http/1.1 OK

Date:sun, Sep 05:04:55 GMT

Server:apache

content-type:text/html; Charset=utf-8

content-length:100

\ r \ n

...

Response Head

The browser primarily wants to know the HTTP protocol version, the return code, the type of content, and the length of the content, regardless of other header fields such as setting cookies. Well, let's consider these items first.

    1. First, the protocol version is fixed to http/1.1
    2. Response code We write an enumeration class status setting
    3. Date if rfc822 format
    4. Content-type and Content-length according to the content

The member variables of the response only need

private Status status;private Map<String, String> heads;private byte[] content;

Let's take a look at date.

Date field

Use a SimpleDateFormat to format the time into rfc822, and note that you want to set locale to 中文版.

SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("EEE, D MMM yyyy HH:mm:ss zzz", locale.english);

But this time zone is not right, then we set the time zone static {Simpledateformat.settimezone ("Timezone.gettimezone (" GMT "));}

Content-type Domain

If the text type needs to be specified by the user, such as JSON. URLConnection.getFileNameMap().getContentTypeFor(path)the MIME type corresponding to the file path is available for use. Also, if the text type, you need to write CharSet.

if (contentType.startsWith("text")) {    contentType += "; charset=" + charset;}
Content-length Domain

Set it to Content.length.

Response body

If the content is a file Files.readAllBytes(FileSystems.getDefault().getPath(path)); , all the bytes can be read. If the content is text, it is good to encode it directly into UTF-8. Of course JSON text is generally, then content-type needs to be set to Application/json; Charset=utf-8. This can be specified by the user.

Back to Bytebuffer

Since the last write Socketchannel requires Bytebuffer, then we need to turn the response into Bytebuffer. Write in format and convert to Bytebuffer.

1 PrivateBytebuffer FinalData =NULL;2  PublicBytebuffer Getbytebuffer () {3     if(FinalData = =NULL) {4Heads.put ("Content-length", String.valueof (content.length));5StringBuilder SB =NewStringBuilder ();6Sb.append (http_version). Append (""). Append (Status.getcode ()). Append (""). Append (Status.getmessage ()). Append ("\r\ N);7          for(Map.entry<string, string>Entry:heads.entrySet ()) {8Sb.append (Entry.getkey ()). Append (":"). Append (Entry.getvalue ()). Append ("\ r \ n").);9         }TenSb.append ("\ r \ n"); One         byte[] head =sb.tostring (). GetBytes (CHARSET); AFinalData = bytebuffer.allocate (head.length + content.length + 2); - Finaldata.put (head); - finaldata.put (content); theFinaldata.put ((byte) ' \ R '); -Finaldata.put ((byte) ' \ n '); -Finaldata.flip ();//Remember, flip is needed here . -     } +     returnFinalData; -}

Here a finaldata is used to save the final result, which cannot be modified once the call is made, and prevents the same content from being sent when repeated reads. Otherwise, hasremaining is true every time it is read.

Write a Web server and framework with your bare hands in Java < chapter II: request and Response>

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.