如何使用request.post(Python)直接发送数组类型的方式

文章讲述了如何利用Python的requests库构造POST请求,特别是如何处理data和json参数,以及转换numpy数组为bytes进行传输。示例中展示了将预测结果转换为JSON格式,设置Content-Type头,然后发送到指定URL的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们先来看一下request的源码

 """Constructs a :class:`Request <Request>`, prepares it and sends it.
        Returns :class:`Response <Response>` object.

        :param method: method for the new :class:`Request` object.
        :param url: URL for the new :class:`Request` object.
        :param params: (optional) Dictionary or bytes to be sent in the query
            string for the :class:`Request`.
        :param data: (optional) Dictionary, list of tuples, bytes, or file-like
            object to send in the body of the :class:`Request`.
        :param json: (optional) json to send in the body of the
            :class:`Request`.
        :param headers: (optional) Dictionary of HTTP Headers to send with the
            :class:`Request`.

可看到入参数有data、json,若还有其他的参数使用可变参数字典形式进行传递了kwargs
data类型传参有字典、列表元祖等类型,json传参就是将参数转化为json格式进行传递的。
传递numpy时,我们一般将数组转为bytes然后传递给data参数。
我们这里举例:
发送数据为

keypoints = result['preds']
dic={}
dic['index']=keypoints.tolist()
dicJson = json.dumps(dic)
headers = {'Content-Type': 'application/json'}
url = 'http://10.11.24.23:8384/getimg'
# response = requests.post(url= url, headers=headers,  data=img_encoded.tobytes())
response = requests.post(url= url, headers=headers,  json=dicJson)

获取数据

pose_results = request.json #获取到json
pose_results = json.loads(pose_results)#list数据
#np.array(pose_results['index']).shape转为numpy
### 使用 `urllib.request.Request` 方法中的 `data` 参数 当使用 Python 的 `urllib.request.Request` 发起 HTTP POST 请求时,可以通过设置 `Request` 对象的 `data` 参数来递数据给服务器。此参数接受的是字节序列形式的数据,通常是对表单数据进行 URL 编码后的结果。 对于想要发送到服务器的数据,首先应将其构建成一个字典对象,接着利用 `parse.urlencode()` 函数将该字典转换成适合网络输的形式,并通过 `.encode('utf-8')` 转换成字节数组[^1]: ```python from urllib import request, parse url = 'https://httpbin.org/post' data_dict = {'key1': 'value1', 'key2': 'value2'} data_encoded = parse.urlencode(data_dict).encode('utf-8') ``` 创建带有 `data` 参数的请求实例时,只需简单地把上述编码好的数据作为第二个参数入即可。这会自动告知 `urllib` 此次请求POST 类型: ```python req = request.Request(url, data=data_encoded, method='POST') ``` 为了确保服务器能够正确处理所提交的内容,在某些情况下可能还需要指定合适的头部信息(Header),比如 Content-Type 和 User-Agent 等。这些可以通过调用 `add_header()` 方法完成配置[^4][^5]: ```python req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") req.add_header("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)") ``` 最后一步就是执行这个已经准备完毕的请求,并读取返回的结果了。这里推荐采用上下文管理器的方式来进行操作,这样可以在完成后自动关闭连接资源: ```python with request.urlopen(req) as response: the_page = response.read().decode('utf-8') print(the_page) ``` 以上即是如何在 `urllib.request.Request` 中运用 `data` 参数的具体方式及其完整的代码示范。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值