http是处于tcp/ip四层网络模型的应用层(最上层),以下图 html
由于它是创建在tcp协议之上的,因此它的底层实现是socket.(笔者猜想HttpUrlConnection与开源工具httpClient都是创建在socket之上的,但没有进行证明,有时间的朋友能够看下源码) java
http 请求格式以下 编程
Method URI Protocol/Version\r\n Request headers \r\n Entity body
Method 是请求方法(get, post, delete, put, head, options, trace), URI是要请求的资源定位符,Protocol/Version是请求协议及版本(这里是HTTP/1.1).各部分之间由CRLF(即"\r\n")分开.(注意请求头的每一个request header也是以\r\n结束的,但headers与entity body 之间还有一个\r\n,具体参见下面实例) tomcat
http 响应格式以下 网络
Protocol/Version Status-code Description\r\n Response headers \r\n Entity body一个典型的http请求以下
这是在笔者的电脑上用firefox请求本地的tomcat所截取的数据包。返回的数据以下 app
好了,下面咱们能够编程模拟get 请求了,代码以下: socket
public class Test { public static void main(String[] args) throws UnknownHostException, IOException { Socket s = new Socket("127.0.0.1", 8080); String method = "GET /index.html HTTP/1.1\r\n"; String host = "Host: localhost:8080\r\n"; OutputStream os = s.getOutputStream(); os.write(method.getBytes()); os.write(host.getBytes()); //注意这个CRLF,不然请求格式不正确,不能发起链接 os.write("\r\n".getBytes()); os.flush(); InputStream is = s.getInputStream(); byte[] buffer = new byte[216]; int count=0; StringBuilder str = new StringBuilder(); while((count=is.read(buffer))>0) { str.append(new String(buffer,0,count)); } s.close(); System.out.println(str.toString()); } }下面是截取的数据包:
返回数据包与上相同,再也不赘述。
tcp