http协议:超文本传输协议
http协议规定,响应与请求一样,有3部分组成,分别是
1.http协议版本、状态代码、描述
2.响应头(response head)
3.响应文本(response content)
实例
http/1.1 200 ok
server:apache tomcat/6.0.12
date:mon,6oct2012 16:35:42 gmt
content-type:text/html;charset=gbk;
content-length:112
下面示例在浏览器中输入http://localhost:8888可以得到响应
package httpserver; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; public class Server { private ServerSocket server; public static final String CRLF = "\r\n"; public static final String BLANK=" "; public static void main(String[] args) { Server server = new Server(); 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); System.out.println(requestInfo); //响应 StringBuilder responseContext = new StringBuilder(); responseContext.append("<html><head><title>HTTP响应示例</title></head><body>hello tomcat!</body></html"); StringBuilder response = new StringBuilder(); //1)http协议版本、状态代码、描述 response.append("HTTP/1.1").append(BLANK).append("200").append(BLANK).append("OK").append(CRLF); //2)响应头(response head) response.append("server:apache tomcat/6.0.12").append(CRLF); response.append("Date:").append(new Date()).append(CRLF); //3.响应文本(response content) response.append("content-type:text/html;charset=gbk;").append(CRLF); //正文长度 response.append("Content-Length;").append(responseContext.toString().getBytes().length).append(CRLF); //正文之前 response.append(CRLF); //正文 response.append(responseContext); //输出了 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); bw.write(response.toString()); bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } /* * 停止 */ public void stop(){ } }
请求头