我的目标是向服务器发送 POST 请求并获得正确的响应。
注意:尖括号代表占位符。
在终端中,使用以下代码将为我提供所需的响应。
curl -u <user>:<pass> -H 'Content-Type: application/xml' -X POST https://<rest of url>
我当前的 PHP 看起来像这样:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); //$uri is the same that I use in terminal
curl_setopt($ch, CURLOPT_USERPWD,
sprintf('%s:%s', $user, $pass)); //same as terminal user & pass
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$headers = array(
'Content-Type: application/xml', //expect an xml response
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$curl_result = curl_exec($ch);
使用此 PHP,我收到 400 Bad Request 错误。
详细信息:
> POST <same url> HTTP/1.1
Authorization: Basic YWRtaW5Ac3Bhcms0NTEuY29tOnNwYXJrc29tZXRoaW5n
Host: <correct host>
Accept: */*
Content-Type: application/xml
Content-Length: -1
Expect: 100-continue
* HTTP 1.0, assume close after body
< HTTP/1.0 400 Bad request
< Cache-Control: no-cache
< Connection: close
< Content-Type: text/html
为什么我在使用 PHP 时收到 400 Bad Request 错误,但在使用命令行时却没有?我该如何解决这个问题,以便使用 PHP 获得我想要的响应?
最佳答案
curl_setopt($ch, CURLOPT_POSTFIELDS, array());
添加这一行后,我的问题就解决了。在某种程度上,这个解决方案是有道理的;但我不明白为什么需要 CURLOPT_POSTFIELDS。在 PHP 文档中,这部分应该包含在 CURLOPT_POST 下,除非这只是意外起作用。
关于php - 如何在 PHP 中发送没有请求数据的 cURL POST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25766306/