PHP cURL - How do I send the body of the request?

使用PHP向API发布请求时遇到问题。我无法控制API服务器,必须以他们请求的格式发送数据。他们唯一真实的文档是以下 CLI 示例:‎

curl -X POST 'http://username:password@domain.tld/foo/bar?param1=false&param2=0' -d 'Hello World!'

使用CURLOPT_POSTFIELDS选项

$ch = curl_init();
$username = "username";
$password = "password";
$data = "Hello World!";

$url = "http://" . $username . ":" . $password . "@domain.tld";
$params = array( "param1"=>"false", "param2"=>0 );

$url .= "?" . http_build_query($params);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$response = curl_exec($ch);
curl_close($ch);

或者

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://username:password@domain.tld/foo/bar?param1=false&param2=0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Hello World!");
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

参考:https://programmierfrage.com/items/php-curl-how-do-i-send-the-body-of-the-request


» 本文链接:https://blog.apires.cn/archives/2064.html
» 转载请注明来源:Java地带  » 《PHP cURL - How do I send the body of the request?》

» 本文章为Java地带整理创作,欢迎转载!转载请注明本文地址,谢谢!
» 部分内容收集整理自网络,如有侵权请联系我删除!

» 订阅本站:https://blog.apires.cn/feed/

标签: PHP

评论已关闭