gpt4 book ai didi

PHP cURL GET 请求和请求的主体

转载 作者:IT王子 更新时间:2023-10-29 01:24:11 24 4
gpt4 key购买 nike

我正在尝试将 cURL 用于这样的 GET 请求:

function connect($id_user){
$ch = curl_init();
$headers = array(
'Accept: application/json',
'Content-Type: application/json',

);
curl_setopt($ch, CURLOPT_URL, $this->service_url.'user/'.$id_user);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
$body = '{}';

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$authToken = curl_exec($ch);

return $authToken;
}

如您所见,我想将 $body 作为请求的主体传递,但我不知道它是否正确,实际上我无法调试,您知道是否有权使用 curl_setopt($ch, CURLOPT_POSTFIELDS,$body); 带有 GET 请求?

因为整个代码与 POST 完美配合,现在我正在尝试将其更改为 GET,如您所见

最佳答案

接受的答案是错误的。 GET 请求确实可以包含一个正文。这就是解决方案 implemented by WordPress ,例如:

curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );

编辑:澄清一下,在这种情况下,初始的 curl_setopt 是必需的,因为在使用 CURLOPT_POSTFIELDS 时,libcurl 会将 HTTP 方法默认为 POST (参见 documentation)。

关于PHP cURL GET 请求和请求的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17230246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com