0. 先明晰幾個概念
- tcp/ip:是傳輸層協(xié)議,主要解決數(shù)據(jù)如何在網(wǎng)絡中傳輸
- http:是應用層的協(xié)議,規(guī)定了如何包裝數(shù)據(jù)。應用層還有很多協(xié)議,比如FTP、TELNET 等
- socket:是對tcp/ip 協(xié)議的封裝,socket 本身并不是協(xié)議,而是一個調(diào)用接口(API),通過socket,我們才能使用tcp/ip 協(xié)議
就是人們<big>約定</big>了一種格式的網(wǎng)絡請求就是http請求。
Question
1.http 這一種約定的格式是怎么樣的呢?
2.這么說socket 也可以來發(fā)http 請求咯?
1.示例:一個常見的http請求和響應
1.1 HTTP 請求
一個 HTTP 請求包括三個組成部分:
- 方法—統(tǒng)一資源標識符(URI)—協(xié)議/版本
- 請求的頭部
- 主體內(nèi)容
下面是一個 HTTP 請求的例子:
POST /examples/default.jsp HTTP/1.1
Accept: text/plain; text/html
Accept-Language: en-gb
Connection: Keep-Alive
Host: localhost
User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
Content-Length: 33
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
lastName=Franks&firstName=Michael
說明:
- 方法—統(tǒng)一資源標識符(URI)—協(xié)議/版本出現(xiàn)在請求的第一行。
- 請求的頭部包含了關(guān)于客戶端環(huán)境和請求的主體內(nèi)容的有用信息。例如它可能包括瀏覽器設(shè)置的語言,主體內(nèi)容的長度等等。每個頭部通過一個回車換行符(CRLF)來分隔的。
- 主體內(nèi)容只是最下面一行
1.2 HTTP 響應
類似于 HTTP 請求,一個 HTTP 響應也包括三個組成部分:
- 方法—統(tǒng)一資源標識符(URI)—協(xié)議/版本
- 響應的頭部
- 主體內(nèi)容
下面是一個 HTTP 響應的例子:
HTTP/1.1 200 OK
Server: Microsoft-IIS/4.0
Date: Mon, 5 Jan 2004 13:13:33 GMT
Content-Type: text/html
Last-Modified: Mon, 5 Jan 2004 13:13:12 GMT
Content-Length: 112
<html>
<head>
<title>HTTP Response Example</title>
</head>
<body>
Welcome to Brainy Software
</body>
</html>
說明:
- 響應頭部的第一行類似于請求頭部的第一行。
- 響應的主體內(nèi)容是響應本身的 HTML 內(nèi)容。
※ 我們不僅知道了http請求的格式,http響應的格式也知道了。而且聰明的你一定發(fā)現(xiàn),用socket來發(fā)送http請求好像的確是可行的,只要按<big>約定</big>的格式發(fā)送請求的消息就可以了。
2.用Socket發(fā)送/接收http請求
我先寫了一個簡單的服務端程序,開放8088端口。
以下的程序相當于,發(fā)送了這樣一個http請求:
GET/api/v1/games HTTP/1.1
Host: localhost:8080
Connection: Close
public static void main(String[] args) throws ParseException, IOException, InterruptedException {
Socket socket = new Socket("127.0.0.1", 8088);
OutputStream os = socket.getOutputStream();
boolean autoflush = true;
PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// send an HTTP request to the web server
out.println("GET /api/v1/games HTTP/1.1");
out.println("Host: localhost:8080");
out.println("Connection: Close");
out.println();
// read the response
boolean loop = true;
StringBuffer sb = new StringBuffer(8096);
while (loop) {
if (in.ready()) {
int i = 0;
while (i != -1) {
i = in.read();
sb.append((char) i);
}
loop = false;
}
Thread.currentThread().sleep(50);
}
// display the response to the out console
System.out.println(sb.toString());
socket.close();
}
拓展閱讀:
HTTP Header 詳解
《How Tomcat Works》