You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Curl、Go/Python HTTP Client发送带Trailers的HTTP请求?

发送带Trailer的HTTP请求(Curl/Go/Python)

要发送带Trailer的HTTP请求,必须满足两个核心条件:

  • 请求头中需包含Trailer字段,明确声明后续要发送的Trailer头名称
  • 请求体必须采用分块编码(Transfer-Encoding: chunked),因为Trailer是附着在分块体的末尾发送的

使用Curl发送

Curl支持通过--trailer参数指定Trailer,同时需显式启用分块编码:

curl -X POST http://example.com \
  -H "Transfer-Encoding: chunked" \
  -H "Trailer: X-Custom-Trailer" \
  --trailer "X-Custom-Trailer=my-trailer-value" \
  --data-binary @- << EOF
这是请求体的内容
EOF

注:部分旧版本Curl可能不支持直接给--trailer赋值,此时需确保请求体为分块格式,Curl会自动在块末尾追加声明的Trailer头。


使用Go发送

Go标准库net/http原生支持Trailer,只需在请求中配置相关字段即可:

package main

import (
	"bytes"
	"fmt"
	"net/http"
)

func main() {
	body := bytes.NewBufferString("请求体内容")
	req, err := http.NewRequest("POST", "http://example.com", body)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 声明要发送的Trailer头
	req.Header.Set("Trailer", "X-Custom-Trailer")
	// 显式指定分块编码(当请求体为未知长度的Reader时,Go会自动设置,此处显式声明更清晰)
	req.TransferEncoding = []string{"chunked"}

	// 设置Trailer头的值
	req.Trailer = http.Header{
		"X-Custom-Trailer": []string{"trailer-demo-value"},
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()

	fmt.Println("响应状态码:", resp.Status)
}

使用Python发送

Python标准库http.client可直接控制分块请求和Trailer发送,示例如下:

import http.client

conn = http.client.HTTPConnection("example.com")

# 构建请求头,声明Trailer和分块编码
headers = {
    "Transfer-Encoding": "chunked",
    "Trailer": "X-Custom-Trailer"
}

# 初始化请求
conn.request("POST", "/", headers=headers)

# 发送分块请求体:格式为【块大小(16进制)\r\n块内容\r\n】
conn.send(b"7\r\n测试内容\r\n")
# 发送结束块
conn.send(b"0\r\n")
# 发送Trailer头,末尾需加两个\r\n表示结束
conn.send(b"X-Custom-Trailer: python-trailer-value\r\n\r\n")

# 获取并输出响应
resp = conn.getresponse()
print("响应状态码:", resp.status)
print("响应内容:", resp.read().decode())
conn.close()

内容的提问来源于stack exchange,提问作者Blaise Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:37:23