我在我的应用程序的客户端有以下代码:
$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方法?
我在网上搜索了这个的解释,但我什么也没找到
如果您使用http PUT
与curl,那么您必须指定Content-Length
头。否则,curl会自动处理GET
和POST
。
例如,如果你发布以下data
与curl与CURLOPT_POSTFIELDS
。然后curl会自动添加data
的长度和标题。
$data = "name=alex&email=none!";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
为了更好地理解,使用verbose模式运行curl代码,您将看到它是如何处理请求和响应的。
curl_setopt($ch, CURLOPT_VERBOSE, true);