【发布时间】:2017-09-26 15:11:16
【问题描述】:
py 请求:
# 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 只存储值:
当使用 application/x-www-form-urlencoded 或 multipart/form-data 作为时,通过 HTTP POST 方法传递给当前脚本的变量关联数组请求中的 HTTP Content-Type。
http://php.net/manual/en/reserved.variables.post.php
所以,我也想使用与 jQuery 默认行为相同的 Python 请求,我该怎么办?
【问题讨论】:
-
我不明白。有什么问题?
-
我知道 PHP 语法,问题是:如何使用 Python 以简单的方式发送像 @weirdan 的答案这样的请求,因为我还想发送一个更复杂的 JSON,其中包含数组。
-
@Viky - 你有没有用 Python 解决这个问题?不知道将数据发送为 a=1&b[]=2&b[]=3&b[]=4 是什么意思,是否意味着每个值都需要作为数组发送?
-
@ShoaibKhan ,是的,我使用 Python 客户端向 PHP 服务器发送数据。我现在写了一个简单的函数来转换它:github.com/vikyd/to_php_post_arr
标签: python json http python-requests content-type