【问题标题】:json Data with POST requests in Python doesn't arrivePython中带有POST请求的json数据未到达
【发布时间】:2014-02-04 22:58:09
【问题描述】:

我喜欢构建一个小的 REST 接口来连接 PYTHON 和 PHP。 经过几个小时的谷歌搜索后,我几乎从几个讨论板上复制和粘贴代码:

import requests
import json

url = 'http://spidercontrol.ilumiweb.local/helge/voltage'

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data = {'value': '7.4', 'decay_time': '300'}

r = requests.post(url, data=json.dumps(data), headers=headers)

这应该通过 POST 将数据作为 json 发送到给定的 url。这是发送到的位置:

<?php

  echo "Method: \t".$_SERVER['REQUEST_METHOD']."\r\n";
  print_r(getallheaders());
  echo "Post:";
  print_r($_POST);
  echo "Get:";
  print_r($_GET);
  exit;
?>

但是 $_POST 数据中什么都没有:

Method:         POST
Array
(
    [Host] => spidercontrol.ilumiweb.local
    [Content-Length] => 37
    [Content-type] => application/json
    [Accept-Encoding] => gzip, deflate, compress
    [Accept] => text/plain
    [User-Agent] => python-requests/2.2.1 CPython/2.7.6 Windows/7
)
Post:Array
(
)
Get:Array
(
)

如果我使用相同的代码,但删除 headers=headers 信息但 data=data 效果很好。有人知道为什么吗?

【问题讨论】:

    标签: php python json post httprequest


    【解决方案1】:

    在 PHP 中,$_POST 仅包含表单数据(application/x-www-form-urlencodedmultipart/form-data 编码的 POST 正文)。

    要获取 JSON 数据,您需要直接使用 php://input 读取请求正文:

    $json = json_decode(file_get_contents("php://input"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2015-09-18
      • 2019-01-06
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多