0

curl查看响应头指定字段:4种高效提取方法详解

2026.05.26 | youres | 10次围观

为什么要查看响应头的指定字段

完整响应头往往有十几行,实际排查问题时通常只关心其中一两个字段。比如:

  • 排查缓存问题 → 只看 Cache-ControlETagLast-Modified
  • 调试登录态 → 只看 Set-Cookie
  • 检查服务器类型 → 只看 ServerX-Powered-By
  • 确认压缩生效 → 只看 Content-Encoding

下面介绍4种在实战中最高效的提取方法。

方法一:grep 直接过滤(最常用)

-I 参数只输出响应头(不下载 body),配合 grep 精准过滤:

# 查看单个指定字段
curl -sI https://www.youres.cn | grep -i "content-type"

# 查看多个指定字段(扩展正则)
curl -sI https://www.youres.cn | grep -iE "content-type|cache-control|server"

# 只显示字段值(去掉字段名)
curl -sI https://www.youres.cn | grep -i "content-type" | cut -d':' -f2-

说明:-s 静默模式,-I 只请求 HEAD(响应头),-i 让 grep 忽略大小写。

方法二:sed/awk 精确提取字段值

需要只获取字段的"值"部分(不含字段名)时,用 sedawk 更干净:

# sed:提取 Content-Type 的值
curl -sI https://www.youres.cn | sed -n 's/^Content-Type:[[:space:]]*//ip'

# awk:提取指定字段的值
curl -sI https://www.youres.cn | awk 'BEGIN{IGNORECASE=1} /^content-type:/ {print }'

注意:HTTP 头字段名不区分大小写,脚本里务必用 IGNORECASE-i 忽略大小写。

方法三:curl -D 写入文件后提取

-D - 将响应头输出到 stdout(- 代表 stdout),方便管道处理:

# 写入 stdout 并过滤
curl -s -D - https://www.youres.cn -o /dev/null | grep -i "set-cookie"

# 写入临时文件再分析
curl -s -D /tmp/headers.txt https://www.youres.cn -o /dev/null
grep -i "cache-control" /tmp/headers.txt

方法四:结合脚本语言处理

用 Python 或 Node.js 解析响应头更灵活:

# Python:提取指定响应头字段
import subprocess, re
headers = subprocess.run(['curl', '-sI', 'https://www.youres.cn'], capture_output=True, text=True).stdout
for line in headers.splitlines():
    if 'content-type' in line.lower():
        print(line.strip())

# Node.js:提取 Content-Type
const { execSync } = require('child_process');
const headers = execSync('curl -sI https://www.youres.cn').toString();
const match = headers.match(/content-type:[^\r\n]+/i);
if (match) console.log(match[0]);

实战:批量检测多个网站的指定响应头

#!/bin/bash
domains=("https://www.youres.cn" "https://www.baidu.com")
for url in ""; do
  echo "===  ==="
  curl -sI "" | grep -iE "server|x-powered-by|content-type"
  echo
done

常见坑与注意事项

  • 重定向会覆盖响应头:-L 跟随重定向时,后续响应头会覆盖前面的,用 -L -D - 可以看到每次跳转的响应头。
  • HTTP/2 响应头强制小写:grep 时务必加 -i 忽略大小写。
  • 字段可能出现多次:Set-Cookie 在同一响应中出现多次,用 head -1 取第一个。

相关文章

版权声明

本文仅代表个人观点。
本文系AI辅助作者原创,未经许可,转载请保留原文链接。

发表评论