【发布时间】:2016-03-27 02:13:17
【问题描述】:
我正在尝试使用 cURL 发送带有 POST 请求的 JSON 文本。 JSON 文本为:
{"channel": "我的频道", "username": "我的用户名", "text": "我的文字"}
我正在使用此代码:
<?php
$data = array(
'username' => 'My username',
'channel' => 'My channel'
'text' => 'My text',
);
$data_json = json_encode($data);
$curl = curl_init('my-url');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_json))
);
$result = curl_exec($curl);
echo $result ;
?>
代码有效,但我想在我的 JSON 文本中添加一个“附件”数组,如下所示:
{"channel": "我的频道", "username": "我的用户名", "text": "我的文字", "attachments": [{"text":"Line 1","color": "#000000"},{"text":"第 2 行","color":"#ffffff"}]}
所以我尝试将它添加到我的 $data 数组中:
'attachments' => '[{"text":"Line 1", "color":"#000000"}, {"text":"Line 2", "color":"#ffffff"}]',
但不起作用,帖子已发送,但我的“附件”被忽略... 我还尝试使用以下代码直接从 Linux 终端发送 POST:
POST https://myurl.com
payload={"channel": "My channel", "username": "My username", "text": "My text", "attachments": [{"text":"Line 1","color":"#000000"},{"text":"Line 2","color":"#ffffff"}]}
而且它正在工作...... 我只是不明白为什么它使用手动 POST 而不是使用 php/curl...
感谢您的回答。
PS:对不起我的英语不好,我是法国人......
【问题讨论】:
-
我懒得去查规则看我能不能用法语回答,所以我暂时还是用英语。忽略“附件”数据是什么意思?您的意思是它们在 $_POST 中不存在吗?还是它们是空的?
-
如何查看?
-
您可以在接收端
var_dump完整的$_POST来查看确切的JSON 字符串。