使用 cURL 发布数据时“需要长度”

问题描述 投票:0回答:6
<h1>Length required</h1>

错误。


$cookie = "Secret cookie data here"; $searchData = array( '__EVENTTARGET' => 'ctl00$main$btn', 'ctl00$main$tbMNr' => $_GET['smth'], 'ctl00$main$tbMb' => $_GET['smthElse'], '__VIEWSTATE' => 'smthElseHere' ); // Commenting this out, as suggested by user lonesomeday //foreach ($searchData as &$elem) // This should not be necessary // $elem = urlencode($elem); // create a new cURL resource $fields = http_build_query($searchData); // Assuming it's an array if ($ch = curl_init("http://mysite.com")) { // set URL and other appropriate options curl_setopt($ch, CURLOPT_COOKIE, $cookie); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, true); // Suggestion from Berry Langerak - no difference, same error curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); } $result = curl_exec($ch); if ($result === false) { echo 'Curl error: ' . curl_error($ch); } echo "<pre>".$fields."</pre>".$result; // For debugging ONLY curl_close($ch);

如果我注释掉 
CURLOPT_POSTFIELDS

CURLOPT_POST
,一切都很好。

有什么建议吗?

编辑

当我添加这一行时

curl_setopt($ch, CURLOPT_HEADER, array('Content-Type:application/x-www-form-urlencoded'));

我在
Length Required

之前看到了这个错误

HTTP/1.1 411 长度必需 内容类型:text/html 日期:2011 年 5 月 16 日星期一 10:20:54 GMT 连接:关闭 内容长度:24

php curl http-post http-error
6个回答
6
投票

    不要自己更改 Content-Length,而是让 libcurl 这样做,以便它变得正确。
  1. 您打算做一个多部分表单帖子(将哈希数组传递给 POSTFIELDS 选项)还是“常规”表单(将字符串传递给 POSTFIELDS 选项)?接收者很可能会假设其中一种,而您不能随意选择一种类型。
  2. 当您有正确的 POST 并且您知道您正确发送了数据(验证记录的浏览器使用情况)时,
  3. 然后

    您可以看到服务器所说的内容,如果它仍然坚持认为有问题,那么您可以回顾记录的内容会话并调整您的请求以使其更类似于该请求。冲洗并重复直至起作用。


4
投票

curl_setopt($ch, CURLOPT_POST, true);

这可能会解决问题。


4
投票

如果您要发布到 IIS 6 并且没有任何内容,您仍然需要发送 Content-Length: 0 否则它会抱怨“Length required”。


1
投票
编辑

:您是否也尝试删除 & ? http_build_query($array, '', '&');

==============

你尝试过评论吗

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));

您的 cookie 数据有效吗?

尝试放置代理:

$agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)"; curl_setopt($ch, CURLOPT_USERAGENT, $agent);

    设置推荐人:
  • curl_setopt($ch, CURLOPT_REFERER,$url);


0
投票


0
投票

设置在卷曲中

© www.soinside.com 2019 - 2024. All rights reserved.