簡體   English   中英

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 中使用以下代碼:

測試.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);

$ php 測試。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 錯誤請求。 有什么我做錯了嗎?

請幫忙。 任何想法將不勝感激。

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

似乎 cURL 會自動添加它,因為您的請求不包含 POST 正文 - 但如果它被設置,它應該設置為0

'Content-Length: 0'添加到$headers數組中,這樣 cURL 就不會將 header 本身添加到錯誤的值。

@choi

你編碼你的令牌了嗎?

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 基本認證

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM