我使用aiohttp(和asyncio)向php应用程序发出post请求。
当我在python上设置json的头时,php应用程序不会收到任何$u post数据(php已经设置了Content-Type: application/json
头)。
php端代码只返回json_encode($_POST)
。
#!/usr/bin/env python3
import asyncio
import simplejson as json
from aiohttp import ClientSession
from aiohttp import Timeout
h = {'Content-Type': 'application/json'}
url = "https://url.php"
d = {'some': 'data'}
d = json.dumps(d)
# send JWS cookie
cookies = dict(sessionID='my-valid-jws')
async def send_post():
with Timeout(5):
async with ClientSession(cookies=cookies, headers=h) as session:
async with session.post(url, data=d) as response:
if (response.status == 200):
response = await response.json()
print(response)
loop = asyncio.get_event_loop()
loop.run_until_complete(send_post())
运行这个我得到:
[]
当删除headers参数和
json.dump(d)
时,我得到:{"some:"data"}
最佳答案
默认情况下,php无法理解application/json
,您必须自己实现它,通常是通过删除如下内容:
if (isset($_SERVER["HTTP_CONTENT_TYPE"]) &&
strncmp($_SERVER["HTTP_CONTENT_TYPE"], "application/json", strlen("application/json")) === 0)
{
$_POST = json_decode(file_get_contents("php://input"), TRUE);
if ($_POST === NULL) /* By default PHP never gives NULL in $_POST */
$_POST = []; /* So let's not change old habits. */
}
在php代码的“公共加载路径”中。
关于php - 使用post和JWS发送JSON数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37305583/