dongzhan5286 2014-03-21 16:22
浏览 368
已采纳

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

while in the server files:

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

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.

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

  • 写回答

1条回答 默认 最新

  • douxuelv7755 2014-03-21 16:29
    关注

    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.

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

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图