【发布时间】:2016-04-12 18:28:09
【问题描述】:
我一直在尝试理解 curl 和构建标题,但似乎无论我做什么,我都会收到以下错误:
HTTP/1.1 400 Bad Request Date: Tue, 12 Apr 2016 18:15:33 GMT Server: Apache/2.2.29 (Unix) mod_wsgi/3.5 Python/2.7.10 PHP/5.6.10 mod_ssl/2.2.29 OpenSSL/0.9.8zh DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.22.0 Content-Length: 226 Connection: close Content-Type: text/html; charset=iso-8859-1
Bad Request
Your browser sent a request that this server could not understand.
以下是我用来发送 post 变量并通过 curl 获取内容的函数。执行提取的文件和提取其内容的文件都在 MAMP 上本地托管
$url = "./lib/otherpage.php";
$data = array("url"=>$_POST["url"],"format"=>"json");
function tryCurl($baseurl,$data)
{
$bodydata = array(json_encode($data));
$bodystr = http_build_query($bodydata);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$baseurl);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$bodystr);
curl_setopt($ch, CURLOPT_PORT,8888);
curl_setopt($ch, CURLOPT_HEADER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER,array(
"POST / HTTP/1.0",
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($bodystr),
"Host: localhost:8888/gt_dev/",
"User-Agent: My-User-Agent 1.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Cache-Control: no-cache",
"Accept-Language: en;q=0.7,en-us;q=0.3",
"Connection: close",
));
// Execute
$result=curl_exec($ch);
// Printing any errors..
echo curl_error($ch);
curl_close($ch);
return $result;
}
最终,请求应该向接收文件发送两个 post 变量(“url”和“format”),并期望返回一个 json 字符串。
【问题讨论】:
-
你试过完整的url路径吗?
-
你试图对标题做太多事情,而且,
$bodydata = array(json_encode($data)); $bodystr = http_build_query($bodydata);完全坏了。 -
@AguV 完整的 url 路径产生相同的结果。 draw010 - 是的,我不知道它应该如何工作,因为我已经尝试了一切。你所指的代码是我从following answer 中提取的
-
你想用 $_POST["url"] 做什么?确保您的
$data不是null。 -
您是要发送 json 还是 form-urlencoded?检查你的 $bodydata 变量!