使用post和JWS

时间:2016-05-18 16:42:42

标签: php python http aiohttp

我使用aiohttp(和asyncio)向PHP应用程序发出POST请求。 当我在python上为json设置头时,PHP应用程序不会收到任何$ _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())

运行这个我得到:[]

删除标题参数和json.dump(d)后,我得到:{"some:"data"}

1 个答案:

答案 0 :(得分:0)

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. */
}

在共同的负载路径中#34;您的PHP代码。