简体   繁体   English

Python中带有POST请求的json数据未到达

[英]json Data with POST requests in Python doesn't arrive

I like to build a small REST Interface to connect PYTHON with PHP. 我喜欢构建一个小的REST接口以将PYTHON与PHP连接。 After some hours of google I ended with nearly copy&paste code from several discussion-boards: Google几个小时后,我从几个讨论区中几乎复制并粘贴了代码:

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)

This should send the data as json via POST to the given url.This is where it's sended to: 这应该通过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;
?>

But there is nothing in the $_POST data: 但是$ _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
(
)

If I use the same code, but remove the headers=headers information but data=data it works well. 如果我使用相同的代码,但删除headers = headers信息,但删除data = data则效果很好。 Did someone know why? 有人知道为什么吗?

In PHP $_POST only contains form data ( application/x-www-form-urlencoded or multipart/form-data encoded POST bodies). 在PHP中, $_POST仅包含表单数据( application/x-www-form-urlencodedmultipart/form-data编码的POST正文)。

To get JSON data you'll need to read the request body directly using php://input instead: 要获取JSON数据,您需要直接使用php://input来读取请求正文:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM