带有参数数据的Python Request Post

sly*_*sid 122 python httprequest http-status-codes python-requests

这是API调用的原始请求:

POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&format=json HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json
Content-Length: 86
Host: 192.168.3.45:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

{"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}"""
Run Code Online (Sandbox Code Playgroud)

此请求返回成功(2xx)响应.

现在我试图使用requests以下命令发布此请求:

>>> import requests
>>> headers = {'content-type' : 'application/json'}
>>> data ={"eventType":"AAS_PORTAL_START","data{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
>>> url = "http://192.168.3.45:8080/api/v2/event/log?sessionKey=9ebbd0b25760557393a43064a92bae539d962103&format=xml&platformId=1"
>>> requests.post(url,params=data,headers=headers)
<Response [400]>
Run Code Online (Sandbox Code Playgroud)

对我来说一切都很好看,我不太确定我发错了什么来得到400响应.

Mar*_*ers 219

params用于GET样式的URL参数,data用于POST样式的主体信息.在请求中提供两种类型的信息是完全合法的,您的请求也是如此,但您已经将URL参数编码到URL中.

您的原始帖子包含JSON数据.requests可以为你处理JSON编码,它也会设置正确Content-Header; 您需要做的就是将要编码为JSON的Python对象传入json关键字参数.

您也可以拆分URL参数:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
Run Code Online (Sandbox Code Playgroud)

然后发布您的数据:

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)
Run Code Online (Sandbox Code Playgroud)

json关键字是新的requests2.4.2版本; 如果您仍然需要使用旧版本,请使用该json模块手动编码JSON 并将编码结果作为data密钥发布; 在这种情况下,您必须显式设置Content-Type标头:

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)
Run Code Online (Sandbox Code Playgroud)


Ion*_*lub 12

将数据设置为:

data ={"eventType":"AAS_PORTAL_START","data":{"uid":"hfe3hf45huf33545","aid":"1","vid":"1"}}
Run Code Online (Sandbox Code Playgroud)

  • 请简要解释一下你所做的与他的数据不同的地方 (8认同)

Noe*_*ans 7

将响应分配给值并测试其属性.这些应该告诉你有用的东西.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
Run Code Online (Sandbox Code Playgroud)
  • 当然,status_code应该只是重新确认之前给出的代码