Python Request Post with param data

前端 未结 3 547
粉色の甜心
粉色の甜心 2020-11-27 09:39

This is the raw request for an API call:

POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&format=json H         


        
相关标签:
3条回答
  • 2020-11-27 10:19

    params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

    Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

    You could split out the URL parameters as well:

    params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
    

    then post your data with:

    import requests
    
    url = 'http://192.168.3.45:8080/api/v2/event/log'
    
    data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
    params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
    
    requests.post(url, params=params, json=data)
    

    The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

    import requests
    import json
    
    headers = {'content-type': 'application/json'}
    url = 'http://192.168.3.45:8080/api/v2/event/log'
    
    data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
    params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
    
    requests.post(url, params=params, data=json.dumps(data), headers=headers)
    
    0 讨论(0)
  • 2020-11-27 10:27

    Assign the response to a value and test the attributes of it. These should tell you something useful.

    response = requests.post(url,params=data,headers=headers)
    response.status_code
    response.text
    
    • status_code should just reconfirm the code you were given before, of course
    0 讨论(0)
  • 2020-11-27 10:32

    Set data to this:

    data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
    
    0 讨论(0)
提交回复
热议问题