4

我正在尝试实现一个小功能来验证可能的网络钓鱼 URL,并认为使用 Google 安全浏览 API 将是一个好的开始。

在阅读了 API 文档后,我想我已经掌握了一些东西,并拼凑了以下代码:

import requests
import json

url = "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=<REDACTED>"
headers = {'content-type': 'application/json'}

payload = {'client': {'clientId': "mycompany", 'clientVersion': "0.1"},
        'threatInfo': {'threatTypes': ["SOCIAL_ENGINEERING", "MALWARE"],
                       'platformTypes': ["ANY_PLATFORM"],
                       'threatEntryTypes': ["URL"],
                       'threatEntries:': [{'url': "http://www.urltocheck1.org"}]}}

print (json.dumps(payload, indent=4))

r = requests.post(url, headers=headers, json=payload)

如果我做一个

print (json.dumps(payload, indent=4)

一切看起来都很好。但是,我从 Google 收到的回复不同意。

{'error': {'message': '收到无效的 JSON 有效负载。\'threat_info\' 中的未知名称“threat_entries:”:找不到字段。','status':'INVALID_ARGUMENT','code':400,'details':[{'@type':'type.googleapis.com /google.rpc.BadRequest', 'fieldViolations': [{'field': 'threat_info', 'description': '收到无效的 JSON 有效负载。未知名称 "threat_entries:" at \'threat_info\': 找不到字段。'}]}]}} {'X-Frame-Options': 'SAMEORIGIN', 'Transfer-Encoding': 'chunked', 'Cache-控制':'私人','日期':'星期二,2016 年 10 月 25 日 07:55:30 GMT','内容类型':'application/json; 字符集=UTF-8','Alt-Svc':'quic=":443"; 马=2592000;v="36,35,34,33,32"', 'X-Content-Type-Options': 'nosniff', 'Content-Encoding': 'gzip', 'X-XSS-Protection': '1; 模式=块','服务器':'ESF'}应用程序/json;字符集=UTF-8

我不能 - 像往常一样 - 发现我的错误。其他人可以发现它并可能让我走上正确的轨道吗?

4

1 回答 1

3

只需删除不必要的冒号threatEntries ,它应该可以正常工作。

此外,如果您使用的是requests2.4.2 或更高版本,则无需content-type在代码中插入标头,而是可以将密钥移动到该params部分:

import requests
import json

api_key='your_key'
url = "https://safebrowsing.googleapis.com/v4/threatMatches:find"
payload = {'client': {'clientId': "mycompany", 'clientVersion': "0.1"},
        'threatInfo': {'threatTypes': ["SOCIAL_ENGINEERING", "MALWARE"],
                       'platformTypes': ["ANY_PLATFORM"],
                       'threatEntryTypes': ["URL"],
                       'threatEntries': [{'url': "http://www.urltocheck1.org"}]}}
params = {'key': api_key}
r = requests.post(url, params=params, json=payload)
# Print response
print(r) 
print(r.json())
于 2016-11-06T22:25:58.240 回答