获取 `POST 请求需要 Content-length header。 ' 当 运行 卷曲代码

Getting `POST requests require a Content-length header. ' when running Curl code

我想通过这个 curl 请求获得一个 Auth2 令牌:

define("CALLBACK_URL", "http://localhost/los/index");
define("AUTH_URL", "https://accounts.google.com/o/oauth2/auth");
define("ACCESS_TOKEN_URL", "https://oauth2.googleapis.com/token");
 define("CLIENT_ID", "**.apps.googleusercontent.com");
define("CLIENT_SECRET", "**");
define("SCOPE", 
"https://www.googleapis.com/auth/admin.directory.device.chromeos"); // optional


 function getToken(){
 $curl = curl_init();

 $params = array(
CURLOPT_URL =>  ACCESS_TOKEN_URL."?"
                ."code=".$code
                ."&grant_type=authorization_code"
                ."&client_id=". CLIENT_ID
                ."&client_secret=". CLIENT_SECRET
                ."&redirect_uri=". CALLBACK_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_NOBODY => false, 
CURLOPT_HTTPHEADER => array(
  "cache-control: no-cache",
  "content-type: application/x-www-form-urlencoded",
  "accept: *",
  "accept-encoding: gzip, deflate",
),
 );

  curl_setopt_array($curl, $params);


   $response = curl_exec($curl);
 $err = curl_error($curl);
  echo $response;
  curl_close($curl);

  if ($err) {
   echo "cURL Error #01: " . $err;
       } else {
 $response = json_decode($response, true);    
    if(array_key_exists("access_token", $response)) return $response;
if(array_key_exists("error", $response)) echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
  }
 }

但是,它给了我这个错误信息: POST requests require a Content-length header. That’s all we know.

我曾尝试删除 URL 中的换行符,但这并没有解决问题。 (我遵循了 this 教程) 我怎样才能解决这个问题?我需要手动输入 content-length header 吗?

您需要将 Content-Length header 添加到 CURLOPT_HTTPHEADER 数组。

该值通常是 body 的大小(以字节为单位)。由于您没有任何值,我建议尝试将 0 作为值。

CURLOPT_HTTPHEADER => array(
  "cache-control: no-cache",
  "content-type: application/x-www-form-urlencoded",
  "accept: *",
  "accept-encoding: gzip, deflate",
  "Content-Length: 0"
)