Several ways to construct http requests (with source code)


foreword

Blogger's Personal Community: Development and Algorithm Learning Community

Blogger Profile: Killing Vibe's Blog

Everyone is welcome to join and exchange and learn together~~

1. The form form constructs an http request

form (form) is a common tag in HTML. It can be used to send GET or POST requests to the server.

Important parameters of form:

  • action: What is the URL of the constructed HTTP request.
  • method: The method of the constructed HTTP request is GET or POST (form only supports GET and POST).

Important parameters of input:

  • type: indicates the type of the input box. text indicates the text, password indicates the password, and submit indicates the submit button.
  • name: Indicates the key of the query string of the constructed HTTP request. The value of the query string is the
    content entered by the user in the input box.
  • value: The value of the input tag. For the submit type, the value corresponds to the text displayed on the button.
 <form method="get" action="/collect">
     <input type="text" name="today">
     <input type="text" name="result">
     <button>提交</button>
</form>
 <form method="post" action="/collect">
    <input type="text" name="today">
    <input type="text" name="result">
    <button>提交</button>
</form>

The following are /collect resources that support get and post requests:

insert image description here

Open the page where you are, enter, and click submit (take post as an example):

insert image description here

Open the network panel of the developer tool to observe:

The request and response headers are:

insert image description here

The request body is: insert image description here
The get method is the same, except that the data in the request body goes to the request header and becomes a query string.

2. Ajax constructs http request

From the perspective of the front end, in addition to the browser address bar can construct GET request, the form form can construct GET and POST, HTTP request can also be constructed through ajax. And the function is more powerful.


The full name of ajax is Asynchronous Javascript And XML. It is a way for JavaScript to send HTTP requests to the server proposed in 2005.
The feature is that data transmission can be performed without refreshing the page/page jump.

In JavaScript, HTTP requests can be constructed through ajax.

<!DOCTYPE html>
<html lang="zh-hans">
<head>
    <meta charset="UTF-8">
    <title>发送有请求体的 ajax 请求</title>
</head>
<body>
    <script src="/js/ajax-send-request-body.js"></script>
</body>
</html>

The following is the js code:

// 1. 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 方法设置要访问的 url
xhr.open('post', '/collect')
// 3. 默认异步处理响应. 需要挂在处理响应的回调函数.
xhr.onload = function() {
    
    
    console.log(xhr)
    console.log(this)
    console.log(this.status)
   console.log(this.getResponseHeader('location')) // header 中的 name 不区分大小写
   console.log(this.responseText)
}

// 区别在这里, 调用 setRequestHeader 设置请求头。设置类型是text类型, 也可以是application/x-www-form-urlencoded 类型
xhr.setRequestHeader('Content-Type', 'text/killingvibe')
// 4. 调用 send 方法发送 http 请求
xhr.send('我随便写,按照 content-type 的格式去写就行')

After entering http://127.0.0.1:8080/ajax-send-request-body.html in the address bar, open the network panel, we can see three request packets,

insert image description here

expand:

To send application/json data, just change the above code below to the following:

// 调用 setRequestHeader 设置请求头
httpRequest.setRequestHeader('Content-Type', 'application/json');
// 4. 调用 send 方法发送 http 请求
httpRequest.send(JSON.stringify({
    
    
name: 'zhangsan',
age: 18
}));

3. Java socket constructs http request

The so-called "send HTTP request" is essentially to write a string into the TCP Socket according to the HTTP format. The
so-called "receive HTTP response" is essentially to read a string from the TCP Socket, and then follow the HTTP format Format to parse.
Based on the knowledge of Socket, we can construct a simple HTTP client program to send various types of HTTP requests.

Client code:

public class MyHttpClient {
    
    
    public static void main(String[] args) throws Exception {
    
    
        // 只能进行一次请求-响应的 HTTP 客户端
        // 主机                  127.0.0.1
        // 端口(进程)           8080
        // 资源路径              /hello.html
        try (Socket socket = new Socket("127.0.0.1", 8080)) {
    
    
            // 准备 HTTP 请求内容
            // 文本   String

            // 格式:请求行
            String requestLine = "GET /hello.html HTTP/1.0\r\n";
            // 请求头:完全可以没有,但必须一个空行结尾
            String requestHeader1 = "Name: killingvibe\r\n\r\n";  // 请求头中共有 1对 key-value
            String requestHeader2 = "Name: killingvibe\r\nAge: 1999\r\n\r\n";    // 请求头中共有 2对 key-value
            String requestHeader3 = "\r\n"; // 请求头中共有 0 对 key-value
            // 请求体,GET 是没有请求体

            // 最终的请求 —— 要发送给服务器的东西
            String request = requestLine + requestHeader3;

            // 发送服务器的过程
            byte[] requestBytes = request.getBytes("ISO-8859-1");   // 字符集编码

            // 发送(数据会经由 TCP、IP、以太网发送给服务器)
            OutputStream os = socket.getOutputStream();
            os.write(requestBytes);
            os.flush();

            // 请求既然已经发送,我们要做的就是等待响应
            InputStream is = socket.getInputStream();
            Scanner scanner = new Scanner(is, "UTF-8"); // 响应的前面字符集应该是 ISO-8859-1,后边是 UTF-8
            while (scanner.hasNextLine()) {
    
    
                String line = scanner.nextLine();
                System.out.println(line);
            }
        }
    }
}

Server code:

public class MyHttpServer {
    
    
    public static void main(String[] args) throws Exception {
    
    
        // 我们也监听在 8080 端口上
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
    
    
            while (true) {
    
    
                Socket socket = serverSocket.accept();  // 三次握手完成

                // 读取用户的请求 :咱这里就不管用户的请求是啥了,一律采用相同的方式返回响应

                // 发送响应
                // Content-Type: 浏览器应该按照什么格式来看到我们响应的资源内容的(资源内容放在响应体中)
                // 响应体(资源的内容)
                String responseBody = "<h1>Welcome MyHttpServer</h1>";
                byte[] responseBodyBytes = responseBody.getBytes("UTF-8");
                int contentLength = responseBodyBytes.length;

                System.out.println("发送响应");
                String response = "HTTP/1.0 200 OK\r\n"
                        + "Server: killingvibeServer\r\n"
                        + "Content-Type: text/plain; charset=utf-8\r\n"       // 响应体的类型
                        + "Content-Length: " + contentLength + "\r\n"        // 响应体的长度
                        + "\r\n";

                byte[] responseBytes = response.getBytes("ISO-8859-1");
                OutputStream os = socket.getOutputStream();
                // TCP 是面向字节流的一种协议,所以只要按顺序发即可,不要管分几次发送
                os.write(responseBytes);    // 先发送前面部分(响应行 和 响应头)
                os.write(responseBodyBytes);    // 再发送响应体
                os.flush();

                // 发送完成之后,直接关闭 TCP 连接(短连接的处理模式)
                socket.close();
            }
        }
    }
}

The console prints the following:

insert image description here

Summarize

The above are the three ways to construct http requests. The summary should be in place. The relevant steps are written in the code comments. If you think it is helpful, you can like it and save it . If there are any deficiencies, welcome to private message bloggers.

Guess you like

Origin blog.csdn.net/qq_43575801/article/details/128823292