JAVA中利用socket实现HTTP请求(二)

2014-11-24 08:44:44 · 作者: · 浏览: 1
nput) {
this.input = input;
}
public void parse() {
// Read a set of 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;
}
}
对应请求要有响应
[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 request) {
this.request = request;
}
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
boolean errorFlag = true;
if(request.getUri()!=null){
File file = new File(HttpServer.WEB_ROOT, request.getUri());
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch != -1) {
output.write(bytes, 0, ch);
ch = fis.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" +
"

File Not Found

";
output.write(errorMessage.getBytes());
}
if (fis != null) {
fis.close();
}
}
}
以上三个简单的类创建好后,我们可以启动HttpServer,然后在 浏览器上输入127.0.0.1:8080 可以看见一个File Not Found,如果想有结果输出到页面上,请配置一个文件在webroot下,例如建一个order.txt,在里面写些内容,也可以弄一个 html,这样就可以在页面上显示你所要看的页面,请求方式就是http://127.0.0.1:8080/order.txt