Python 获取 Request Body 的方法

在 Python 中,我们可以使用 `requests` 库来发送 HTTP 请求并获取请求体(Request Body)的内容。`requests` 库提供了 `request.json()` 和 `request.text` 方法来获取请求体的 JSON 数据和字符串数据。

以下是如何使用 `requests` 库获取请求体内容的示例:

python

import requests

# 发送 HTTP 请求

response = requests.get('https://example.com/api/endpoint', data={'key': 'value'})

# 获取请求体中的 JSON 数据

json_data = response.json()

print(json_data)

# 获取请求体中的字符串数据

text_data = response.text

print(text_data)

在上面的示例中,我们发送了一个 `GET` 请求,并在请求体中包含了 `key=value` 的数据。然后我们使用 `response.json()` 方法来获取 JSON 格式的请求体数据,并使用 `response.text` 方法来获取字符串格式的请求体数据。

如果你需要获取表单数据或者文件上传的数据,你可以使用 `request.form` 或者 `request.files` 来获取这些数据。

python

# 发送包含表单数据的 HTTP 请求

response = requests.post('https://example.com/api/endpoint', data={'key': 'value'})

# 获取表单数据

form_data = response.form

print(form_data)

# 获取上传的文件

files = response.files

print(files)

在 `POST` 请求中,我们可以使用 `data` 参数来包含表单数据,并在 `response.form` 中获取这些数据。对于文件上传,我们可以在 `files` 参数中包含上传的文件,并在 `response.files` 中获取这些文件。

更多文章请关注《万象专栏》