简体   繁体   中英

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 -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; see the doc at 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. 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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