使用JSON数据的Python HTTP请求是没有得到与JSON数据PHP响应(Python HTT

2019-10-29 08:10发布

我想送一些JSON数据蟒蛇HTTP请求(我将在以后的情况下使用该JSON数据)到服务器。 服务器应该给人以(使用PHP)一些JSON数据的响应。 不幸的是,即使请求的状态代码没有任何响应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);

}
 ?>

Answer 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);
?>


Answer 2:

检查你的$ _ POST结构。

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


文章来源: Python HTTP request with json data isn't getting php response with json data