如何在请求正文中使用JSON发出GET请求

2024-04-26 11:09:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在GET请求中发送这个JSON数组

{"user": "jähn", "id": 3}

我试着用

^{pr2}$

但是它的失败是:TypeError:POST数据应该是字节或字节的iterable。它不能是str类型

另一件我觉得很奇怪的事情是它告诉我关于POST数据的信息,尽管我在请求上设置了GET的方法。在

因为这是一个简单的脚本,所以我不希望使用像python请求这样的库


Tags: 数据idjson类型get字节数组iterable
1条回答
网友
1楼 · 发布于 2024-04-26 11:09:49

不能使用JSON编码的主体来发出GET请求,因为GET请求只由URL和头组成。参数是使用URL编码编码编码到URL中的,因此没有将这些参数编码为JSON的选项。在

使用^{} function创建URL编码的参数,然后用?附加到URL。在

from request.parse import urlencode

data = {"user": "jähn", "id": 3}  # note, a Python dictionary, not a JSON string
parameters = urlencode(data)
response = urllib.request.urlopen('?'.join((self.update_url, parameters)))

不要使用data参数;使用该关键字参数会强制请求使用POST方法:

data must be a bytes object specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format.

相关问题 更多 >