我只是想在 PHP 中复制这个 curl 命令:
curl -X POST -H 'Content-Type: application/xml' -u username:password https://api.company.com/api/path
这是我正在使用的 PHP 代码:
$ch = curl_init("https://api.company.com/api/path");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/xml"));
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch); // $response is null
$info = curl_getinfo($ch); // $info['http_code'] is 400
当我的 shell 命令成功并且我从服务器取回数据时,这个 PHP 代码失败了——服务器返回 400 错误。据我所知,PHP 代码和 shell 命令实际上是相同的,那么我缺少什么区别?
编辑:
这是我从详细模式获得的信息:
* About to connect() to api.company.com port 443 (#0)
* Trying xxx.xxx.xxx.xxx...
* connected
* Connected to api.company.com (xxx.xxx.xxx.xxx) port 443 (#0)
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using AES256-SHA
* Server certificate:
* [...]
* SSL certificate verify ok.
* Server auth using Basic with user 'username'
> POST /api/path HTTP/1.1
Authorization: Basic [...]
Host: api.company.com
Accept: */*
Content-Type: application/xml
Content-Length: -1
Expect: 100-continue
< HTTP/1.1 400 BAD_REQUEST
< Content-Length: 0
< Connection: Close
<
* Closing connection #0
编辑 2
我尝试将以下内容添加到脚本中:
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
但这并没有改变服务器的响应。