curl 在 CLI 中有效,但在 PHP 中无效

curl works in CLI, but not in PHP

curl 在 CLI 中有效,但在 PHP 中无效。

以下命令在命令行中有效:

curl -X POST --header "Content-Type: application/json" --header "Authorization: Basic [token]" https://api.example.com/v1/token -v -k

* About to connect() to api.example.com port 443 (#0)
..

> POST /v1/token HTTP/1.1
> User-Agent: curl/7.29.0
> Host: api.example.com
> Accept: */*
> Content-Type: application/json
> Authorization: Basic [token]
> 
< HTTP/1.1 200 OK
< Date: Fri, 30 Apr 2021 02:52:24 GMT
< Content-Type: application/json; charset=utf-8
< Content-Length: 325
< Connection: keep-alive
< X-Powered-By: Express
< ETag: W/"145-rseWkvhNxxhur+O7jUfApznKiww"
< 
* Connection #0 to host api.example.com left intact
{"accesstoken":"token","type":"Bearer","expired":"20210501115224"}

并在 PHP 中使用以下代码:

test.php

<?php
$host = 'https://api.example.com/v1/token';

$headers = array(
    'Content-Type: application/json',
    'Authorization: Basic [token]'
);

$oCurl = curl_init();
curl_setopt($oCurl, CURLOPT_URL, $host);
curl_setopt($oCurl, CURLOPT_POST, true);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($oCurl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($oCurl, CURLOPT_VERBOSE, true);

$response = curl_exec($oCurl);

curl_close($oCurl);

$phptest.php

* About to connect() to api.example.com port 443 (#0)
..

> POST /v1/token HTTP/1.1
Host: api.example.com
Accept: */*
Content-Type: application/json
Authorization: Basic [token]
Content-Length: -1
Expect: 100-continue

< HTTP/1.1 100 Continue
< HTTP/1.1 400 Bad Request
< Server: nginx
< Date: Fri, 30 Apr 2021 04:22:08 GMT
< Content-Type: text/html
< Content-Length: 150
< Connection: close
< 
* Closing connection 0

结果是 HTTP 状态代码 400 错误请求。我做错了什么吗?

请帮忙。 任何想法将不胜感激。

@崔

你对令牌进行编码了吗?

ej.

$host = 'https://api.example.com/v1/token';

$token = base64_encode('username:Password0..');
$headers = array(
    'Content-Type: application/json',
    'Authorization: Basic ' . $token
);

$oCurl = curl_init();
curl_setopt($oCurl, CURLOPT_URL, $host);
...

回应

$> php curl_test.php
*   Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> POST /v1/token HTTP/1.1
Host: 127.0.0.1:8080
Accept: */*
Content-Type: application/json
Authorization: Basic dXNlcm5hbWU6UGFzt3dtcmQwLi4=

* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx
< Date: Fri, 30 Apr 2021 06:50:59 GMT
< Content-Type: application/json; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
...

参考:curl basic auth

Content-Length: -1 看起来很奇怪。

似乎 cURL 会自动添加它,因为您的请求不包含 POST body - 但它应该设置为 0,如果它被设置的话.

'Content-Length: 0' 添加到您的 $headers 数组,这样 cURL 就不会添加错误值的 header 本身。