Python HTTP request with json data isn't getting php response with json data

北城余情 提交于 2019-12-25 01:25:29

问题


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

}
 ?>


回答1:


You should remove quotes on assignment of postMessage in your:

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

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



回答2:


Check your $_POST structure.

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


来源:https://stackoverflow.com/questions/56341180/python-http-request-with-json-data-isnt-getting-php-response-with-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!