简体   繁体   中英

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:

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)

The following php code return 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
$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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