简体   繁体   English

未能发送 php post 请求,但使用 curl 成功

[英]failed to send php post request but succeed with curl

I am trying to send a php post request to my rocket chat server, I was able to do that using curl from command line by using this command from rocket chat api:我正在尝试向我的火箭聊天服务器发送一个 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" }'

But using php I never succeed to do that (by using curl or without)但是使用 php 我从来没有成功过(通过使用 curl 或不使用)

The following php code return false:以下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);

?>

Thank you for your help感谢您的帮助

php has a (parital) wrapper for libcurl, the same library that the curl cli program use under the hood to do requests, you can just use libcurl from php. 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM