带有JSON数据的Python HTTP请求未获得带有JSON数据的php响应 [英] Python HTTP request with json data isn't getting php response with json data

查看:136
本文介绍了带有JSON数据的Python HTTP请求未获得带有JSON数据的php响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将带有一些json数据的python http请求(将在以后的情况下使用此json数据)发送到服务器.服务器应使用json数据给出响应(使用PHP).不幸的是,即使请求状态代码为200,也没有任何响应.请提供任何帮助!

I am trying to send a python http request with some json data (I will use this json data in a later case) to server. Server should give a response with some json data (using PHP). Unfortunately there is no any response even though request status code is 200. Any help please!

#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的引用:

You should remove quotes on assignment of postMessage in your:

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

并将您的php代码更改为:

And change your php code to:

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

这篇关于带有JSON数据的Python HTTP请求未获得带有JSON数据的php响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆