【问题标题】:failed to send php post request but succeed with curl发送 php post 请求失败,但 curl 成功
【发布时间】:2018-03-06 13:23:06
【问题描述】:

我正在尝试向我的 Rocket 聊天服务器发送一个 php 发布请求,我可以通过使用来自 Rocket 聊天 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);

?>

感谢您的帮助

【问题讨论】:

  • http_build_query json_encode 内容?尝试一个/或,而不是两个......看看这是否会有所作为。

标签: php curl post rocket.chat


【解决方案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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 2020-08-28
    • 2017-05-31
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    相关资源
    最近更新 更多