java手动实现HTTP响应response

来源:互联网 发布:端口占用查询工具 编辑:程序博客网 时间:2024/09/21 09:03
public class Response {
private int len;
private static final String BLANK = " ";
private static final String CRLF = "\r\n";
//输出流
private BufferedWriter bw;
//头部
private StringBuilder headContent;
//正文
private StringBuilder content;

public Response() {
headContent = new StringBuilder();
content = new StringBuilder();
}


public Response(Socket socket) {
this();
try {
bw = new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//构建头部
public void head(int code) {
//1)  HTTP协议版本、状态代码、描述
headContent.append("HTTP/1.1").append(BLANK);
switch(code) {
case 200 :
headContent.append("200").append(BLANK).append("OK");
break;
case 404:
headContent.append("404").append(BLANK).append("NOT Found");
break;
case 500:
headContent.append("500").append(BLANK).append("SERVER ERROR");
break;
}


headContent.append(CRLF);
//2)  响应头(Response Head)
headContent.append("Server:haojunjie Server/0.0.1").append(CRLF);
headContent.append("Date:").append(new Date()).append(CRLF);
headContent.append("Content-type:text/html;charset=GBK").append(CRLF);
//正文长度 :字节长度
headContent.append("Content-Length:").append(len).append(CRLF);
//3)正文之前
headContent.append(CRLF);
len += headContent.length();
}
//构建正文
public void content(String str) {
content.append(str);
len += str.length();
}

public void pushToClient(int code) {
head(code);
try {
bw.append(headContent);
bw.append(content);
bw.flush();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}


public class Server4 {
private ServerSocket server;
public static final String CRLF="\r\n";
public static final String BLANK=" ";
/**
* @param args
*/
public static void main(String[] args) {

Server4 server = new Server4();
server.start();


}
/**
* 启动方法
*/
public void start(){
try {
server = new ServerSocket(8888);
this.receive();
} catch (IOException e) {
e.printStackTrace();
}

}
/**
* 接收客户端
*/
private void receive(){
try {
Socket client =server.accept();
byte[] data=new byte[20480];
int len =client.getInputStream().read(data);
//接收客户端的请求信息
String requestInfo=new String(data,0,len).trim();
System.out.println(requestInfo);


//响应

Response rep=new Response(client);
rep.content("<html><head><title>HTTP响应示例</title>");
rep.content("</head><body>我是最强王者</body></html>");
rep.pushToClient(200);



} catch (IOException e) {
}
}

/**
* 听着服务器
*/
public void stop(){

}
}

阅读全文
0 0
原创粉丝点击