1

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

シェル コマンドは成功し、サーバーからデータが返されますが、この PHP コードは失敗します。サーバーは 400 エラーを返します。私の知る限り、PHP コードとシェル コマンドは事実上同一です。


編集:

詳細モードから取得した情報は次のとおりです。

* 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);

しかし、これはサーバーの応答を変更しませんでした。

4

1 に答える 1

1

欠けていた部品を見つけました。明示的CURLOPT_POSTFIELDSに null に設定する必要がありました:

curl_setopt($ch, CURLOPT_POSTFIELDS, null);

その行を追加すると、シェル コマンドと同じように動作するようになります。

于 2013-09-18T15:55:02.983 に答える