我爱编程

[java] 理解http

2017-01-05  本文已影响32人  linzebingo

0. 先明晰几个概念

就是人们<big>约定</big>了一种格式的网络请求就是http请求。

Question
1.http 这一种约定的格式是怎么样的呢?
2.这么说socket 也可以来发http 请求咯?

1.示例:一个常见的http请求和响应

1.1 HTTP 请求

一个 HTTP 请求包括三个组成部分:

下面是一个 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

说明:

1.2 HTTP 响应

类似于 HTTP 请求,一个 HTTP 响应也包括三个组成部分:

下面是一个 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>

说明:

※ 我们不仅知道了http请求的格式,http响应的格式也知道了。而且聪明的你一定发现,用socket来发送http请求好像的确是可行的,只要按<big>约定</big>的格式发送请求的消息就可以了。

2.用Socket发送/接收http请求

我先写了一个简单的服务端程序,开放8088端口。
以下的程序相当于,发送了这样一个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》

上一篇 下一篇

猜你喜欢

热点阅读