php 使用邮递员通过原始 json 发送 POST 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39008071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send POST data via raw json with postman
提问by Dallas
I've got Postman (the one that doesn't open in Chrome) and I'm trying to do a POST request using raw json.
我有邮递员(那个不能在 Chrome 中打开的邮递员),我正在尝试使用原始 json 执行 POST 请求。
In the Body tab I have "raw" selected and "JSON (application/json)" with this body:
在正文选项卡中,我选择了“原始”和带有此正文的“JSON(应用程序/json)”:
{
"foo": "bar"
}
For the header I have 1, Content-Type: application/json
对于标题,我有 1, Content-Type: application/json
On the PHP side I'm just doing print_r($_POST);
for now, and I'm getting an empty array.
在 PHP 方面,我现在只是在做print_r($_POST);
,我得到了一个空数组。
If I use jQuery and do:
如果我使用 jQuery 并执行以下操作:
$.ajax({
"type": "POST",
"url": "/rest/index.php",
"data": {
"foo": "bar"
}
}).done(function (d) {
console.log(d);
});
I'm getting as expected:
我得到了预期的结果:
Array
(
[foo] => bar
)
So why isn't it working with Postman?
那么为什么它不与 Postman 一起工作呢?
Postman screenshots:
邮递员截图:
and header:
和标题:
采纳答案by meda
Unlike jQuery
in order to read raw JSON
you will need to decode it in PHP.
与jQuery
读取原始数据不同,JSON
您需要在 PHP 中对其进行解码。
print_r(json_decode(file_get_contents("php://input"), true));
php://input
is a read-only stream that allows you to read raw data from the request body.
php://input
是一个只读流,允许您从请求正文中读取原始数据。
$_POST
is form variables, you will need to switch to form
radiobutton in postman
then use:
$_POST
是表单变量,您需要切换到form
单选按钮postman
然后使用:
foo=bar&foo2=bar2
To post raw json
with jquery
:
要发布的原始json
带jquery
:
$.ajax({
"url": "/rest/index.php",
'data': JSON.stringify({foo:'bar'}),
'type': 'POST',
'contentType': 'application/json'
});
回答by Itachi
回答by CoredusK
meda's answer is completely legit, but when I copied the code I got an error!
meda 的回答完全合法,但是当我复制代码时出现错误!
Somewhere in the "php://input"
there's an invalid character (maybe one of the quotes?).
某处"php://input"
有一个无效字符(也许是引号之一?)。
When I typed the "php://input"
code manually, it worked.
Took me a while to figure out!
当我"php://input"
手动输入代码时,它起作用了。我花了一段时间才弄清楚!
回答by Neo
I was facing the same problem, following code worked for me:
我遇到了同样的问题,以下代码对我有用:
$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);
回答by Jaroslav ?treit
Install Postman native app, Chrome extension has been deprecated. (Mine was opening in own window but still ran as Chrome app)
安装 Postman 原生应用,Chrome 扩展已被弃用。(我的在自己的窗口中打开,但仍作为 Chrome 应用程序运行)