JAVA
网络
Request类——>HTTP请求
通过传递从Socket对象那里获取的java.io.InputStream对象来构造这个类的实例
调用InputStream对象的read方法来获取HTTP请求原始数据
import java.io.InputStream;
import java.io.IOException;
public class Request {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public void parse() {
}
private String parseUri(String requestString) {
}
public String getUri() {
return uri;
}
}
该方法解析HTTP请求中的原始数据
通过调用private方法parseUri获取的HTTP请求的URI,parseUri把URI存储到uri变量中,
调用public方法getUri来返回HTTP请求的URI
GET /index.html HTTP/1.1
使用GET方法请求index.html文件
public void parse() {
//Read a set of characters from the socket
StringBuilder request = new StringBuilder(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());
}
parse方法从传递给Request的套接字的InputStream那里读取所有字节流,并将字节数组存储在缓存中,然后用缓存字节数组中的字节填入一个叫request的StringBuilder 中
将StringBuilder的字符串形式传递给parseUri方法
private String parseUri(String requestString) {
index1 = requestString.indexOf(' ');
int index2;
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2>index1) {
return requestString.substring(index1 + 1, index2);
}
}
return null;
}
parseUri方法从请求行获取URI
Response类
——>HTTP响应
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.path;
import java.nio.file.paths;
HTTP Response =
Status-Line (( general-header | response-header | entity-header )
CRLF)
CRLF
[ message-body ]
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream ouput;
this.output = output;
}
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
Path path = Paths.get(System.getProperty("user.dir"),
"webroot", request.getUri());
if (Files.exists(path)) {
try (InputStream inputStream =
Files.newInputStream(path)) {
int ch = inputStream.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
output.write(bytes, 0, ch);
ch = inputStream.read(bytes, 0, BUFFER_SIZE);
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
//file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n"
+ "Content-Type: text/html\r\n"
+ "Content-Lengh: 23\r\n" + "\r\n"
+ "<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
}
}