简体   繁体   English

如何为等效的 curl 命令发送 python 请求帖子?

[英]How to send a python requests post for an equivalent curl command?

Hi你好

Following curl command works and am trying to post the same (with a different JSON data )using requests.post and running into below error shown,any guidance on what is wrong?以下 curl 命令有效,我正在尝试使用requests.post发布相同的(使用不同的 JSON 数据)并遇到以下显示的错误,关于什么是错误的任何指导?

curl -vk "https://splunk-hec.company.com:8088/services/collector" -H "Authorization: {token id }" -d '{"sourcetype": "source","index":"indexname", "event": {"a": "value1", "b": ["value1_1", "value1_2"]}}'

PYTHON CODE:-蟒蛇代码:-

_raw = {

    "Total_radar_count":"999",
    "Analyze":{
        "Screen":{"count":110,"radar_link":"change://problem/50411162&42639456&44776863&43703933"},
        "Investigate":{"count":065,"radar_link":"change://problem/50411162&42639456&44776863&43703933"},
        "Review":{"count":106,"radar_link":"change://problem/50411162&42639456&44776863&43703933"}
    },
    "timestamp": int(time.time())  # Can also use datetime.datetime.now().isoformat()
}
url = 'https://splunk-hec.company.com:8088/services/collector?sourcetype=source?index=indexname'
json = _raw
auth_token = 'token id'
head = {'Authorization': auth_token}
response = requests.post(url, json=json, headers=head)
print(response)
print (response.reason)
print(response.json())

ERROR:-错误:-

<Response [400]>
Bad Request
{u'text': u'No data', u'code': 5}

400 (Bad Request) can be many things; 400 (Bad Request) 可以是很多东西; see the doc at https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 .请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400 上的文档。 Next debugging step is to get out wireshark and look at the difference between the two requests.下一个调试步骤是取出wireshark 并查看两个请求之间的差异。 Obviously your data is different between the two, so it could be rejecting it just based on what it expects.显然你的数据在两者之间是不同的,所以它可能会根据它的期望拒绝它。

Also check the server-side log.还要检查服务器端日志。 Chances are the real error is in there.真正的错误很可能在那里。

Try using尝试使用

requests.post(url, headers=head, data=json.dumps(json))

You also need to import json package but don't wory it is a built in package您还需要导入 json 包,但不要担心它是内置包

This question is quite old.这个问题很老了。 However, I thought to share this as I think it may helpful others.但是,我想分享这个,因为我认为它可能对其他人有帮助。 Just try adding "event": for you json post data.只需尝试添加"event":为您 json 发布数据。

response = requests.post(url, json={"event": json}, headers=headers)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM