当 CURLOPT_HTTPHEADER 需要“Content-Length”时

2024-04-24

我的应用程序的客户端中有此代码:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 
    'Content-Type: application/json', 
    'Content-Length:0 ' ) 
    ); 
$body = curl_exec($ch);

在服务器文件中:

$ch = curl_init($this->modelAddress);
$data = array("params"=>array("resource" => "artist","operation" => $operation,"params"=>$params));
$data_string = json_encode($data);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);

它们是由两个不同的人制作的,我想问哪个是最正确的。
当使用'Content-Length:0'代替'Content-Length:'.strlen($data_string)更好。

这只是 POST/GET 方法的问题吗?
我在网上搜索了这方面的解释,但一无所获


如果您使用httpPUT使用curl,那么你必须指定Content-Length标头。否则,它会由两个卷曲自动处理GET and POST.

例如,如果您发布以下内容data与卷曲与CURLOPT_POSTFIELDS。然后curl会自动加上长度data与标题。

$data = "name=alex&email=none!";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

为了更好地理解,请使用详细模式运行您的curl代码,您将看到它如何处理请求和响应。

curl_setopt($ch, CURLOPT_VERBOSE, true);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 CURLOPT_HTTPHEADER 需要“Content-Length”时 的相关文章

随机推荐