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

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line