【问题标题】:Python HTTP request with json data isn't getting php response with json data带有 json 数据的 Python HTTP 请求没有得到带有 json 数据的 php 响应
【发布时间】:2019-05-28 11:27:03
【问题描述】:

我正在尝试向服务器发送一个带有一些 json 数据的 python http 请求(我将在后面使用这个 json 数据)。服务器应该给出一些 json 数据的响应(使用 PHP)。不幸的是,即使请求状态代码是 200,也没有任何响应。请帮助!

#request.py

import requests
import urllib3
import json
import os
import time
import sys

#http Request
url = 'http://localhost/response.php'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:

    postMessage = '{"Info": {"ID": 1, "IP": "192.168.1.1"}}'
    response = requests.post(url, json=postMessage, headers=headers)
    #trying to decode the response
    try:
        decodedresponse = json.loads(response.text) 
        print(decodedresponse)

    except(ValueError, KeyError, TypeError):
        print("some Error")

#always getting the above print statement!

    break
#response.php


<?php

if(!empty($_POST['json'])){
  $data = [ 'a', 'b', 'c' ];  
  header('Content-type:application/json;charset=utf-8');
  echo json_encode($data);

}
 ?>

【问题讨论】:

  • postMessage = {"Info": {"ID": 1, "IP": "192.168.1.1"}}
  • @OlvinR​​oght 还是同样的问题
  • 因为您正在尝试查找不存在的帖子字段json
  • $data = file_get_contents("php://input"); 然后echo json_decode($data);
  • @OlvinR​​oght 我遇到了同样的错误!

标签: php python http httprequest httpresponse


【解决方案1】:

您应该删除在您的postMessage 分配的引号:

postMessage = {"Info": {"ID": 1, "IP": "192.168.1.1"}}

并将您的 php 代码更改为:

<?php
$data = file_get_contents("php://input");
header('Content-type:application/json;charset=utf-8');
echo json_encode($data);
?>

【讨论】:

    【解决方案2】:

    检查您的 $_POST 结构。

    <?php
    if(!empty($_POST['Info'])){
       $data = [ 'a', 'b', 'c' ];  
       echo json_encode($data);
     }
     else{
         echo json_encode(ison_decode($_POST, TRUE));
     }
    

    【讨论】:

    • 我犯了错误,现在尝试不带 json_encode,因为发布数据是 json,我们不需要 json_encode。
    • 上述代码有效。但我意识到只有 else 语句正在执行。 !!!不知道为什么
    • 因为您没有或为空 $_POST['json']... 再次检查您的帖子数据结构。我对答案检查进行了更改,然后重试。
    • 没办法,如果语句不起作用。 echo $_POST 什么也不做。所以输出是相同的(JSON 错误)。问题是空的 $_POST['json'] 。也尝试了您的新代码。给 else 一些数据,例如 $dataElse = [ 'a', 'b', 'c' ];回声 json_encode($dataElse);它奏效了
    • 我做了更改,现在试试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多