gpt4 book ai didi

带有参数数据的 Python 请求发布

转载 作者:IT老高 更新时间:2023-10-28 21:06:41 25 4
gpt4 key购买 nike

这是 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"}}"""

此请求返回成功 (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]>

对我来说一切都很好,但我不太确定我发布的错误是什么以获得 400 响应。

最佳答案

params 用于 GET 样式的 URL 参数,data 用于 POST 样式的正文信息。在请求中提供两种类型的信息是完全合法的,您的请求也这样做,但是您已经将 URL 参数编码到 URL 中。

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

您也可以拆分 URL 参数:

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

然后通过以下方式发布您的数据:

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)

json 关键字是 requests 版本 2.4.2 中的新关键字;如果您仍然需要使用旧版本,请使用 json 模块手动对 JSON 进行编码,并将编码结果作为 data 键发布;在这种情况下,您必须明确设置 Content-Type header :

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)

关于带有参数数据的 Python 请求发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15900338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com