1

I'm using aiohttp (and asyncio) to make a POST request to a PHP application. When I set the header for json on python the PHP application do not receive any $_POST data (PHP have Content-Type: application/json header setted).

The php side code just returns the 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())

Running this I got: []

When removing the headers param and the json.dump(d) I get: {"some:"data"}

4

1 に答える 1

1

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 コードの「共通ロード パス」内。

于 2016-05-23T15:49:30.757 に答える