当CURLOPT_HTTPHEADER需要'Content-Length' [英] when CURLOPT_HTTPHEADER need 'Content-Length'

查看:126
本文介绍了当CURLOPT_HTTPHEADER需要'Content-Length'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序的客户端中有以下代码:

I have this code in the client side of my application:

$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))                                                                       
);

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

They are made from 2 different people and I want to ask what is the most correct.
When the use of 'Content-Length:0' instead of 'Content-Length:'.strlen($data_string) is better.

这是POST/GET方法的唯一问题吗?
我在网络上搜索了有关此内容的说明,但未找到任何内容

It's only question of POST/GET method?
I've searched explanations of this in the web but I've found nothing

推荐答案

如果使用带有curl的http PUT ,则必须指定 Content-Length 标头.否则,它将由curl自动为 GET POST 进行处理.

If you use http PUT with curl then you have to specify the Content-Length header. Otherwise it is automatically handled by the curl for both GET and POST.

例如,如果要使用 CURLOPT_POSTFIELDS 用curl发布以下 data .然后curl将自动将 data 的长度与标头相加.

For example if you are posting the following data with curl with CURLOPT_POSTFIELDS. Then curl will automatically add the length of the data with the header.

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

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

For better understand, run your curl code using verbose mode and you'll see how its handling the requests and responses.

curl_setopt($ch, CURLOPT_VERBOSE, true);

这篇关于当CURLOPT_HTTPHEADER需要'Content-Length'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆