使用php发送GET请求时出现HTTP 400 BAD REQUEST错误

时间:2014-07-01 14:14:26

标签: php http web request

虽然我尝试向GET地址发送php个请求,但收到了HTTP 400 BAD REQUEST消息,我无法找出原因。

这是我的代码:

function redirect($url)
{
    error_reporting(E_ERROR | E_PARSE);

    $components = parse_url($url);

    $port = $components["port"];
    $ip = $components["host"];
    $path = $components["path"];

    //create and connect socket with the parameters entered by the user
    //$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

    echo "Establishing connection to the given adress...\n";


    //Connection timeout limit is set to 10 seconds...
    if(!isset($port))
    {
        $port = 80;
    }
    $sock = fsockopen($ip, $port,$errno, $errstr, 10) or die("Unable to connect...");

    $request = "GET $path HTTP/1.1" . "\r\n\r\n";


    fwrite($sock, $request);

    while ($header = stream_get_line($sock, 1024, "\r\n")) {
        $response.= $header . "\n";
    }
    echo $response;
    $loc = "";

    if (preg_match("/Location:\'(.*)\\n/", $response, $results))
        $loc = $results[1];

    echo $loc;

}

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

GET请求还包含一个标题,其中包含编码使用的内容,您应该查看需要发送的内容以及可选的内容

答案 1 :(得分:0)

针对这个具体问题,我找到了解决方案。如果您想从上面问题中发送的请求中获取标题,可以使用php的get_headers($url)方法。它检索我正在寻找的标头。我对协议和网络服务以及php(1或1.5周)都很陌生,因此我可能会问一个愚蠢的问题并且不够具体。无论如何,非常感谢你的答案。

度过美好的一天!