使用 post 和 JWS 发送 JSON 数据
send JSON data with post and JWS
我正在使用 aiohttp(和 asyncio)向 PHP 应用程序发出 POST 请求。
当我在 python 上为 json 设置 header 时,PHP 应用程序没有收到任何 $_POST 数据(PHP 有 Content-Type: application/json
header 已设置)。
php 边码只是 returns 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 代码的 "common load path" 中。
我正在使用 aiohttp(和 asyncio)向 PHP 应用程序发出 POST 请求。
当我在 python 上为 json 设置 header 时,PHP 应用程序没有收到任何 $_POST 数据(PHP 有 Content-Type: application/json
header 已设置)。
php 边码只是 returns 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 代码的 "common load path" 中。