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

时间:2017-04-28 13:19:19

标签: python json http python-requests content-type

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请求,我该怎么办?

1 个答案:

答案 0 :(得分:1)

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

所以你需要让你的python脚本发送a=1&b[]=2&b[]=3&b[]=4,然后PHP端的$_POST将如下所示:

[ 'a' => 1, 'b' => [ 2, 3, 4] ] 
相关问题