Python 使用 content-type=x-www-form-urlencoded 请求 POST json 数据

标签 python json http python-requests content-type

请求:

# coding=utf-8
from __future__ import print_function

import requests

headers = {
    # 'content-type': 'application/json',
    'content-type': 'application/x-www-form-urlencoded',
}

params = {
    'a': 1,
    'b': [2, 3, 4],
}

url = "http://localhost:9393/server.php"
resp = requests.post(url, data=params, headers=headers)

print(resp.content)

php 接收:

// get HTTP Body
$entityBody = file_get_contents('php://input');
// $entityBody is: "a=1&b=2&b=3&b=4"

// get POST 
$post = $_POST;
// $post = ['a' => 1, 'b' => 4] 
// $post missing array item: 2, 3

因为我还使用 jQuery Ajax POST,默认内容类型 = application/x-www-form-urlencoded。而 PHP 默认 $_POST 只存储值:

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

http://php.net/manual/en/reserved.variables.post.php

所以,我也想像 jQuery 默认行为一样使用 Python 请求,我该怎么办?

最佳答案

PHP 将只接受带有方括号的变量的多个值,表示一个数组(参见 this FAQ entry )。

所以你需要让你的 python 脚本发送 a=1&b[]=2&b[]=3&b[]=4 然后在 PHP 端发送 $_POST看起来像这样:

[ 'a' => 1, 'b' => [ 2, 3, 4] ] 

关于Python 使用 content-type=x-www-form-urlencoded 请求 POST json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681229/

相关文章:

python2.7名称 '__path__'未定义

python - 使用 Resnet 的图像生成器

python - "enumeration"这个习语是如何工作的?

jquery - Tornado 服务器未返回带有 self.write 的响应

java - 在Java中序列化JSON数据是一种有效的方法吗?

angular - 如何创建跨域请求?

java - 从 odesign Sirius 文件导出图表/节点

javascript - 从数据库中输出得到的json数据

Java/Scala 与 Linux 原生的非阻塞 (http) io

css - @fontface 适用于 http ://www. domain.com 但不适用于 http ://domain. com