我正在尝试向我的火箭聊天服务器发送一个php post请求,我能够通过使用来自火箭聊天api的命令从命令行使用curl来做到这一点:
curl -H "X-Auth-Token: xxxxx" -H
"X-User-Id: yyyyy" -H "Content-type:application/json"
http://example:3000/api/v1/chat.postMessage -d '{ "channel":
"#general", "text": "Halo from Germany" }'
但是使用php我从来没有成功(通过使用curl或没有)
以下php代码返回false:
<?php
$url = 'http://example:3000/api/v1/chat.postMessage';
$data = json_encode(array('channel' => '#general', 'text' => 'Halo from Germany'));
$options = array( 'http' => array( 'header' => 'Content-type: application/json', 'X-Auth-Token' => 'xxxxx', 'X-User-Id' => 'yyyyyy', 'method' => 'POST', 'content' => http_build_query($data) ) );
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
?>
感谢您的帮助
答案 0 :(得分:1)
php有一个(parital)libcurl的包装器,与curl cli程序在引擎盖下用来做请求的库相同,你可以只使用来自php的libcurl。
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_HTTPHEADER => array (
"X-Auth-Token: xxxxx",
"X-User-Id: yyyyy",
"Content-type:application/json"
),
CURLOPT_URL => 'http://example:3000/api/v1/chat.postMessage',
CURLOPT_POSTFIELDS => json_encode ( array (
"channel" => "#general",
"text" => "Halo from Germany"
) )
) );
curl_exec ( $ch );
curl_close($ch);