【问题标题】:Keep getting 400 error with cURL on localhost在本地主机上使用 cURL 不断收到 400 错误
【发布时间】: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 变量!

标签: php json curl


【解决方案1】:

这并不是对原始问题的回答,但事实证明我以错误的方式思考我的问题。

我想使用页面 A 作为页面 B 的代理。并传递页面 A 预期的相同变量页面 B。

事实证明,只需包含页面 B 即可实现相同的效果,而不是将预期的参数卷曲到它。所以答案就是

include("./lib/otherpage.php");

【讨论】:

    猜你喜欢
    • 2020-12-23
    • 2020-11-11
    • 2012-06-28
    • 1970-01-01
    • 2016-04-30
    • 2012-01-15
    • 2022-11-26
    • 2019-04-20
    • 2018-02-12
    相关资源
    最近更新 更多