当CURLOPT_HTTPHEADER需要'Content-Length'时

And*_*_86 0 php curl

我在我的应用程序的客户端有这个代码:

$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);
Run Code Online (Sandbox Code Playgroud)

在服务器文件中:

$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))                                                                       
);
Run Code Online (Sandbox Code Playgroud)

它们由2个不同的人组成,我想问最正确的是什么.
当使用'Content-Length:0'而不是'Content-Length:'.strlen($data_string)更好.

这是POST/GET方法的唯一问题?
我在网上搜索了这个解释,但我什么都没发现

Sab*_*san 5

如果你使用PUTcurl的http ,那么你必须指定Content-Length标题.否则,它会自动卷曲两种处理GETPOST.

例如,如果您data使用curl 发布以下内容CURLOPT_POSTFIELDS.然后curl会自动添加data标题的长度.

$data = "name=alex&email=none!";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Run Code Online (Sandbox Code Playgroud)

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

curl_setopt($ch, CURLOPT_VERBOSE, true);
Run Code Online (Sandbox Code Playgroud)