Python请求使用content-type为x-www-form-urlencoded的POST方式发送JSON数据

3

Python 请求:

# 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仅存储值:

使用HTTP POST方法通过application/x-www-form-urlencodedmultipart/form-data作为请求中的HTTP Content-Type时,传递到当前脚本的变量的关联数组。

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

因此,我想要与jQuery默认行为相同地使用Python请求,我该怎么做?


我不明白。有什么问题吗? - FrankBr
我知道PHP语法,问题是:我如何像@weirdan的答案那样简单地使用Python发送请求,因为我还想发送一个包含数组的更复杂的JSON。 - vikyd
@Viky - 你在Python中解决了这个问题吗?不确定weirdan的意思是将数据发送为a=1&b [] = 2&b [] = 3&b [] = 4,这是否意味着每个值都需要作为数组发送? - Shoaib Khan
@ShoaibKhan,是的,我使用Python客户端向PHP服务器发送数据。我编写了一个简单的函数来进行转换,现在可以在这里找到它:https://github.com/vikyd/to_php_post_arr - vikyd
1个回答

2

PHP只能接受含有方括号的变量的多个值,表示一个数组(参见此FAQ条目)。

因此,您需要让Python脚本发送a=1&b[]=2&b[]=3&b[]=4,然后在PHP端,$_POST将如下所示:

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

请参阅parse_str()。其中一些评论涉及此问题。 - DaSourcerer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接