带有json数据的Python HTTP请求没有得到带有json d的php响应

2024-03-28 19:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向服务器发送一个包含一些json数据的pythonhttp请求(稍后我将使用这个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);

}
 ?>


Tags: the数据importjsonhttpurlapplicationresponse
2条回答

您应该在您的中删除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);
?>

检查你的$邮政结构。你知道吗

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

相关问题 更多 >