- Http 1.1协议基本内容
Http 请求:
【1】请求方法--统一资源标识符--协议/版本
【2】请求头
【3】CRLF(回车(CR)换行(LF))
【4】请求实体
样例如下:
POST /index.html HTTP/1.1
Accept: text/plain; text/html
Connection: keep-Alive
Connect-length: 33
Content-type: application/x-www-form-urlencode
lastName=Franks&firstName=Michael
- Http响应:
【1】协议--状态码--描述
【2】响应头
【3】CRLF(空行)
【4】响应实体
样例如下:
HTTP/1.1 200 OK
Content-Type: text/html
Content-length: 112
Http ResponseExampple
Welcome to Brainy Software
这里的Html片段在实际的响应中是一个将会是一个字节流。
备注:我们的请求/响应都必须是严格按照规范上定义的去构造的,否则将会导致请求无效或者响应无效,因为浏览器就是按照这个标准去包装和解析数据的。下面举例实现一个简单的Http服务器:
- 简单的Http服务构建
Request.java
package com.ex01;
import java.io.IOException;
import java.io.InputStream;
/**
* @program: tomcat work
* @description:
* @author: ggr
* @create: 2019-06-14 16:26
**/
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
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.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);
if (index2 > index1) {
return requestString.substring(index1 + 1, index2);
}
}
return null;
}
public String getUri() {
return uri;
}
}
Response.java
package com.ex01;
import java.io.*;
/**
* @program: tomcat work
* @description:
* @author: ggr
* @create: 2019-06-14 16:29
**/
public class Response {
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
public Response(OutputStream output) {
this.output = output;
}
public void setRequest(Request request) {
this.request = request;
}
/*** 这里将按照上面Response的结构一行一行地构造,如果丢失了正常的结构将会导致
* 浏览器无法正常解析这个响应,并认为这个一个无效的响应
*/
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(request.getUri().substring(1));
try {
output.write(("HTTP/1.1 200 OK\n" + "Content-Type: text/html; charset=utf-8\r\n").getBytes());
int available = resourceAsStream.available();
output.write(("Content-Length: " + available + "\n").getBytes());
output.write("Connection: close\r\n".getBytes());
int ch = resourceAsStream.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
output.write(bytes, 0, ch);
ch = resourceAsStream.read(bytes, 0, BUFFER_SIZE);
}
} catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString());
} finally {
if (resourceAsStream != null) {
resourceAsStream.close();
}
}
}
}
HttpServer.java
package com.ex01;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @program: tomcat work
* @description:
* @author: ggr
* @create: 2019-06-14 16:29
**/
public class HttpServer {
public static final String WEB_ROOT = "webRoot";
// shutdown command
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 {
serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
}
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.sendStaticResource();
// Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
}