问题
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