php - 如何在 PHP 中发送没有请求数据的 cURL POST?

标签 php http post curl

我的目标是向服务器发送 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/

相关文章:

javascript - 如何以 hash_hmac PHP (SHA1) 形式获取 CryptoJS 结果

php - 在 Yii 中使用不带 activeRecord 的 mysql IN 子句时如何防止 mysql 注入(inject)?

php - 在 PHP 中打印 MongoDB 对象 _id

php - 向 mySQL 添加数据时使用 PHP POST 变量?

javascript - 为什么当我在 AJAX 中使用 POST 将数据发送到 PHP 时,它说变量为空?

php - 是否可以使用 PHP 的 ID 更改 HTML 元素属性?

http - 将服务请求重定向到另一台服务器

C http O_NONBLOCK 模式问题?

apache - 为什么 HTTP 服务器禁止在 HTTP header 名称中使用下划线

php - php : 1000 fields per POST. 内的新限制有人知道,如果数字会受到影响吗?