未能发送php post请求但成功卷曲

问题描述 投票:1回答:1

我正在尝试向我的火箭聊天服务器发送一个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);

?>

谢谢您的帮助

php curl post rocket.chat
1个回答
1
投票

php有一个(部分)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);
© www.soinside.com 2019 - 2024. All rights reserved.