无法使用 cloudflare 和 python 请求进行 dns-over-https

Unable to make dns-over-https with cloudflare and python requests

我正在尝试编写一个快速脚本,该脚本可以使用新的 1.1.1.1 DNS over HTTPS public 来自 CloudFlare 的 DNS 服务器进行 DNS 查找。

在这里查看他们的文档 https://developers.cloudflare.com/1.1.1.1/dns-over-https/json-format/ 我不确定我做错了什么以及为什么我收到 415 状态代码(415 不受支持的内容类型)。

这是我的脚本: #!/usr/bin/envpython 导入请求 导入 json 从 pprint 导入 pprint

url = 'https://cloudflare-dns.com/dns-query'
client = requests.session() 

json1 = {'name': 'example.com','type': 'A'}

ae = client.get(url, headers = {'Content-Type':'application/dns-json'}, json = json1)


print ae.raise_for_status()
print ae.status_code

print ae.json()

client.close()

这是输出:

    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 415 Client Error: Unsupported Media Type for url: https://cloudflare-dns.com/dns-query

以及 json 响应(我相信是预期的):

raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

使用 curl 效果非常好。

非常感谢

您根本不应该设置 JSON 请求 响应使用JSON.

application/dns-json 值放入 ct 参数中:

JSON formatted queries are sent using a GET request. When making requests using GET, the DNS query is encoded into the URL. An additional URL parameter of ‘ct’ should indicate the MIME type (application/dns-json).

GET 请求从来没有正文,所以不要尝试发送 JSON:

params = {
    'name': 'example.com',
    'type': 'A',
    'ct': 'application/dns-json',
}
ae = client.get(url, params=params)

演示:

>>> import requests
>>> url = 'https://cloudflare-dns.com/dns-query'
>>> client = requests.session()
>>> params = {
...     'name': 'example.com',
...     'type': 'A',
...     'ct': 'application/dns-json',
... }
>>> ae = client.get(url, params=params)
>>> ae.status_code
200
>>> from pprint import pprint
>>> pprint(ae.json())
{'AD': True,
 'Answer': [{'TTL': 2560,
             'data': '93.184.216.34',
             'name': 'example.com.',
             'type': 1}],
 'CD': False,
 'Question': [{'name': 'example.com.', 'type': 1}],
 'RA': True,
 'RD': True,
 'Status': 0,
 'TC': False}