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

使用Python Requests对接Cloudflare DNS over HTTPS时遭遇415错误求助

解决Cloudflare DoH查询返回415 Unsupported Content Type的问题

嗨,我看你在写Python脚本调用Cloudflare的1.1.1.1 DNS over HTTPS服务时碰到了415错误,这个问题我之前也踩过坑,其实根源很明确——请求头的内容类型设置不对!

Cloudflare的JSON格式DoH接口有严格的要求:它只接受application/dns-json类型的请求,而且需要同时设置Accept和Content-Type两个请求头。如果你的脚本没设置这两个头,或者设置成了普通的application/json,服务器就会返回415错误,因为它无法识别你发送的请求格式。

我帮你修正了脚本,补上了关键的请求头设置,两种请求方式(GET/POST)都给你列出来了:

方式一:GET请求(参数放在URL中)

#!/usr/bin/env python
import requests
from pprint import pprint

url = 'https://cloudflare-dns.com/dns-query'

# 定义DNS查询参数,这里以查询example.com的A记录为例
query_params = {
    'name': 'example.com',
    'type': 'A'
}

# 必须设置的请求头,缺一不可
request_headers = {
    'Accept': 'application/dns-json',
    'Content-Type': 'application/dns-json'
}

# 发起GET请求
response = requests.get(url, params=query_params, headers=request_headers)

if response.status_code == 200:
    pprint(response.json())
else:
    print(f"请求失败,状态码: {response.status_code}")
    print(f"响应详情: {response.text}")

方式二:POST请求(参数放在请求体中)

如果更倾向于用POST传递参数,只需要调整请求方式,头信息保持不变:

#!/usr/bin/env python
import requests
from pprint import pprint

url = 'https://cloudflare-dns.com/dns-query'

# 定义DNS查询参数
query_data = {
    'name': 'example.com',
    'type': 'A'
}

request_headers = {
    'Accept': 'application/dns-json',
    'Content-Type': 'application/dns-json'
}

# 发起POST请求,用json参数自动序列化数据
response = requests.post(url, json=query_data, headers=request_headers)

if response.status_code == 200:
    pprint(response.json())
else:
    print(f"请求失败,状态码: {response.status_code}")
    print(f"响应详情: {response.text}")

关键注意点

  • 别把application/dns-json写成application/json,这是最容易犯的错误,也是导致415的核心原因
  • 不管用GET还是POST,Accept和Content-Type两个头都必须设置,服务器会同时校验这两个字段

你可以把自己的脚本对照着改一下,应该就能正常拿到DNS查询结果了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:18:45