【问题标题】:Python request POST json data using content-type=x-www-form-urlencodedPython 使用 content-type=x-www-form-urlencoded 请求 POST json 数据
【发布时间】: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-urlencodedmultipart/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


【解决方案1】:

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

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

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

【讨论】:

  • 另见parse_str()。一些 cmets 解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2019-02-04
  • 2017-09-22
  • 2014-03-30
  • 2011-09-13
  • 2017-08-29
  • 2016-01-27
  • 1970-01-01
  • 2019-06-14
相关资源
最近更新 更多