HTTP Request and Response

本文深入浅出地介绍了HTTP协议的工作原理,包括请求-响应周期、URL、方法、头部和主体等核心概念,并通过实例展示了如何使用这些组件进行有效的API通信。

Reference: https://zapier.com/learn/apis/chapter-2-protocols/

In Chapter 1, we got our bearings by forming a picture of the two sides involved in an API, the server and the client. With a solid grasp on the who, we are ready to look deeper into how these two communicate. For context, we first look at the human model of communication and compare it to computers. After that, we move on to the specifics of a common protocol used in APIs.

Knowing the Rules

People create social etiquette to guide their interactions. One example is how we talk to each other on the phone. Imagine yourself chatting with a friend. While they are speaking, you know to be silent. You know to allow them brief pauses. If they ask a question and then remain quiet, you know they are expecting a response and it is now your turn to talk.

Computers have a similar etiquette, though it goes by the term "protocol." A computer protocol is an accepted set of rules that govern how two computers can speak to each other. Compared to our standards, however, a computer protocol is extremely rigid. Think for a moment of the two sentences "My favorite color is blue" and "Blue is my favorite color." People are able to break down each sentence and see that they mean the same thing, despite the words being in different orders. Unfortunately, computers are not that smart.

For two computers to communicate effectively, the server has to know exactly how the client will arrange its messages. You can think of it like a person asking for a mailing address. When you ask for the location of a place, you assume the first thing you are told is the street address, followed by the city, the state, and lastly, the zip code. You also have certain expectations about each piece of the address, like the fact that the zip code should only consist of numbers. A similar level of specificity is required for a computer protocol to work.

The Protocol of the Web

There is a protocol for just about everything; each one tailored to do different jobs. You may have already heard of some: Bluetooth for connecting devices, and POP or IMAP for fetching emails.

On the web, the main protocol is the Hyper-Text Transfer Protocol, better known by its acronym, HTTP. When you type an address like http://example.com into a web browser, the "http" tells the browser to use the rules of HTTP when talking with the server.

With the ubiquity of HTTP on the web, many companies choose to adopt it as the protocol underlying their APIs. One benefit of using a familiar protocol is that it lowers the learning curve for developers, which encourages usage of the API. Another benefit is that HTTP has several features useful in building a good API, as we'll see later. Right now, let's brave the water and take a look at how HTTP works!

HTTP Requests

Communication in HTTP centers around a concept called the Request-Response Cycle. The client sends the server a request to do something. The server, in turn, sends the client a response saying whether or not the server could do what the client asked.

Figure 1. The Request-Response Cycle.

To make a valid request, the client needs to include four things:

  1. URL (Uniform Resource Locator) 1
  2. Method
  3. List of Headers
  4. Body

That may sound like a lot of details just to pass along a message, but remember, computers have to be very specific to communicate with one another.

URL

URLs are familiar to us through our daily use of the web, but have you ever taken a moment to consider their structure? In HTTP, a URL is a unique address for a thing (a noun). Which things get addresses is entirely up to the business running the server. They can make URLs for web pages, images, or even videos of cute animals.

APIs extend this idea a bit further to include nouns like customers, products, and tweets. In doing so, URLs become an easy way for the client to tell the server which thing it wants to interact with. Of course, APIs also do not call them "things", but give them the technical name "resources."

Method

The request method tells the server what kind of action the client wants the server to take. In fact, the method is commonly referred to as the request "verb."

The four methods most commonly seen in APIs are:

  • GET - Asks the server to retrieve a resource
  • POST - Asks the server to create a new resource
  • PUT - Asks the server to edit/update an existing resource
  • DELETE - Asks the server to delete a resource

Here's an example to help illustrate these methods. Let's say there is a pizza parlor with an API you can use to place orders. You place an order by making a POST request to the restaurant's server with your order details, asking them to create your pizza. As soon as you send the request, however, you realize you picked the wrong style crust, so you make a PUT request to change it.

While waiting on your order, you make a bunch of GET requests to check the status. After an hour of waiting, you decide you've had enough and make a DELETE request to cancel your order.

Headers

Headers provide meta-information about a request. They are a simple list of items like the time the client sent the request and the size of the request body.

Have you ever visited a website on your smartphone that was specially formatted for mobile devices? That is made possible by an HTTP header called "User-Agent." The client uses this header to tell the server what type of device you are using, and websites smart enough to detect it can send you the best format for your device.

There are quite a few HTTP headers that clients and servers deal with, so we will wait to talk about other ones until they are relevant in later chapters.

Body

The request body contains the data the client wants to send the server. Continuing our pizza ordering example above, the body is where the order details go.

A unique trait about the body is that the client has complete control over this part of the request. Unlike the method, URL, or headers, where the HTTP protocol requires a rigid structure, the body allows the client to send anything it needs.

These four pieces — URL, method, headers, and body — make up a complete HTTP request.

Figure 2. The structure of an HTTP request.

HTTP Responses

After the server receives a request from the client, it attempts to fulfill the request and send the client back a response. HTTP responses have a very similar structure to requests. The main difference is that instead of a method and a URL, the response includes a status code. Beyond that, the response headers and body follow the same format as requests.

Status Codes

Status codes are three-digit numbers that each have a unique meaning. When used correctly in an API, this little number can communicate a lot of info to the client. For example, you may have seen this page during your internet wanderings:

Figure 3. A default 404 web page.

The status code behind this response is 404, which means "Not Found." Whenever the client makes a request for a resource that does not exist, the server responds with a 404 status code to let the client know: "that resource doesn't exist, so please don't ask for it again!"

There is a slew of other statuses in the HTTP protocol, including 200 ("success! that request was good") to 503 ("our website/API is currently down.") We'll learn a few more of them as they come up in later chapters.

After a response is delivered to the client, the Request-Response Cycle is completed and that round of communication over. It is now up to the client to initiate any further interactions. The server will not send the client any more data until it receives a new request.

Figure 4. The structure of an HTTP response.

How APIs Build on HTTP

By now, you can see that HTTP supports a wide range of permutations to help the client and server talk. So, how does this help us with APIs? The flexibility of HTTP means that APIs built on it can provide clients with a lot of business potential. We saw that potential in the pizza ordering example above. A simple tweak to the request method was the difference between telling the server to create a new order or cancel an existing one. It was easy to turn the desired business outcome into an instruction the server could understand. Very powerful!

This versatility in the HTTP protocol extends to other parts of a request, too. Some APIs require a particular header, while others require specific information inside the request body. Being able to use APIs hinges on knowing how to make the correct HTTP request to get the result you want.


Chapter 2 Recap

The goal of this chapter was to give you a basic understanding of HTTP. The key concept was the Request-Response Cycle, which we broke down into the following parts:

  • Request - consists of a URL (http://…), a method (GET, POST, PUT, DELETE), a list of headers (User-Agent…), and a body (data).
  • Response - consists of a status code (200, 404…), a list of headers, and a body.

Throughout the rest of the course, we will revisit these fundamentals as we discover how APIs rely on them to deliver power and flexibility.


Homework

Use the form below to make the following list of requests and see what responses you are given.

Instructions

  1. Send a GET request without any body data.
  2. Send a POST request and type your favorite kind of pizza in the body field.
  3. Send a PUT request and type a new ingredient to add to your pizza in the body field.
  4. Send a DELETE request without any body data.

Form

https://zapier.com/learn/apis/chapter-2-protocols/

  •        
  •        
  •        
  •        
  •      
  • Response

    You haven't ordered a pizza yet. Maybe try a different method?

    在 IEEE 802.11 标准中,**BlockAck(块确认)机制**是用于提高无线网络中数据传输效率的重要机制。为了启用 BlockAck,必须先通过 **ADDBA(Add Block Ack)握手协议**建立一个 **BlockAck 协商过程**。这个过程包括: - **ADDBA Request(添加块确认请求)** - **ADDBA Response(添加块确认响应)** --- ## ✅ 一、ADDBA RequestResponse 的作用 ### 1. **ADDBA Request** - 由**发送端(Tx)**发送给**接收端(Rx)** - 请求建立一个 BlockAck 协商 - 包含参数如: - BlockAck Policy(立即或延迟确认) - TID(Traffic Identifier) - 窗口大小(最大允许未确认帧数) - 超时时间(Timeout) - BA 机制是否启用 ### 2. **ADDBA Response** - 接收端收到请求后,根据自身资源和能力决定是否接受请求 - 返回响应帧,包含: - 是否接受请求(成功或拒绝) - 支持的 BlockAck 参数(TID、窗口大小等) --- ## ✅ 二、帧格式说明 ### ✅ 1. **ADDBA Request 帧结构(简化)** | 字段 | 长度 | 说明 | |------|------|------| | Category | 1 byte | 值为 3(BlockAck 相关) | | Action | 1 byte | 值为 0(表示 Add BlockAck 请求) | | Dialog Token | 1 byte | 用于匹配请求与响应 | | BA Parameter Set | 2 bytes | BlockAck 参数集合 | | Timeout | 2 bytes | 超时时间(单位:TU) | | Starting Sequence Control | 2 bytes | 起始序列号(低 12 位) | ### ✅ 2. **ADDBA Response 帧结构** | 字段 | 长度 | 说明 | |------|------|------| | Category | 1 byte | 值为 3 | | Action | 1 byte | 值为 1(表示响应) | | Dialog Token | 1 byte | 与请求中的 Token 一致 | | Status Code | 2 bytes | 状态码(0 表示成功) | | BA Parameter Set | 2 bytes | 接收端接受的 BlockAck 参数 | | Timeout | 2 bytes | 接收端接受的超时时间 | | Starting Sequence Control | 2 bytes | 起始序列号 | --- ## ✅ 三、流程说明(BlockAck 建立过程) ``` 发送端发送 ADDBA Request ↓ 接收端收到请求,判断是否接受 ↓ 接收端发送 ADDBA Response(成功或拒绝) ↓ 若成功,双方建立 BlockAck 协商,后续使用 BlockAck 帧确认数据帧 ``` --- ## ✅ 四、C语言示例:模拟 ADDBA RequestResponse 帧的构造 ```c #include <stdio.h> #include <stdint.h> #include <string.h> // ADDBA Request 帧结构体 typedef struct { uint8_t category; uint8_t action; uint8_t dialog_token; uint16_t ba_parameter_set; uint16_t timeout; uint16_t start_seq_ctrl; } __attribute__((packed)) ADDBA_Request; // ADDBA Response 帧结构体 typedef struct { uint8_t category; uint8_t action; uint8_t dialog_token; uint16_t status_code; uint16_t ba_parameter_set; uint16_t timeout; uint16_t start_seq_ctrl; } __attribute__((packed)) ADDBA_Response; // 构造 ADDBA Request 帧 void build_addba_request(ADDBA_Request *req, uint8_t tid, uint16_t window_size, uint8_t dialog_token) { req->category = 3; // BlockAck category req->action = 0; // ADDBA Request req->dialog_token = dialog_token; // BA Parameter Set: TID(4位) + BlockAck Policy(1位) + TID Present(1位) + Reserved(10位) req->ba_parameter_set = (tid & 0x0F) | ((uint16_t)1 << 1) | ((uint16_t)1 << 2); // Immediate BlockAck, TID present req->timeout = 0xFFFF; // 默认最大超时 req->start_seq_ctrl = 0x0000; // 起始序列号从 0 开始 } // 构造 ADDBA Response 帧 void build_addba_response(ADDBA_Response *resp, const ADDBA_Request *req, uint16_t status_code) { resp->category = req->category; resp->action = 1; // ADDBA Response resp->dialog_token = req->dialog_token; resp->status_code = status_code; // 如果接受请求,返回相同的参数 if (status_code == 0) { resp->ba_parameter_set = req->ba_parameter_set; resp->timeout = req->timeout; resp->start_seq_ctrl = req->start_seq_ctrl; } else { // 拒绝请求,其他参数可设为默认 resp->ba_parameter_set = 0; resp->timeout = 0; resp->start_seq_ctrl = 0; } } int main() { ADDBA_Request req; ADDBA_Response resp; // 构造 ADDBA Request build_addba_request(&req, 5, 64, 0x12); printf("ADDBA Request 构造完成,TID: %d\n", req.ba_parameter_set & 0x0F); // 构造 ADDBA Response(成功) build_addba_response(&resp, &req, 0); printf("ADDBA Response 构造完成,状态码: %d\n", resp.status_code); return 0; } ``` --- ## ✅ 五、代码解释 - 定义 `ADDBA_Request` 和 `ADDBA_Response` 结构体,模拟 IEEE 802.11 中的帧格式。 - `build_addba_request()` 函数构造 ADDBA 请求帧,包含协商参数。 - `build_addba_response()` 函数构造响应帧,根据是否接受请求返回不同参数。 - 主函数中演示如何使用这两个函数。 --- ## ✅ 六、关键字段解释 | 字段 | 含义 | |------|------| | `category` | 表示该帧属于 BlockAck 类别(值为 3) | | `action` | 0 表示请求,1 表示响应 | | `dialog_token` | 用于匹配请求与响应 | | `ba_parameter_set` | 包括 TID、BlockAck Policy(立即或延迟)、窗口大小等 | | `status_code` | 0 表示接受,非零表示拒绝 | | `start_seq_ctrl` | BlockAck 的起始序列号 | --- ## ✅ 七、总结 | 内容 | 说明 | |------|------| | ✅ ADDBA Request | 发送端发起 BlockAck 协商请求 | | ✅ ADDBA Response | 接收端响应请求,返回是否接受 | | ✅ BlockAck Policy | 可以是 Immediate 或 Delayed | | ✅ BlockAck 机制 | 提高无线网络吞吐量,减少 ACK 开销 | | ✅ BlockAck 建立过程 | 必须通过 ADDBA 握手建立协商 | --- ###
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值