http協議之get請求原理(socket請求web內容)

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

相關文章
相關標籤/搜索