dsfw2154
2014-07-01 14:14 阅读 171
已采纳

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

While I'm trying to send a GET request to an address with php I receive HTTP 400 BAD REQUEST message and I can't figure out why.

Here's my code:

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...
";


    //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" . "

";


    fwrite($sock, $request);

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

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

    echo $loc;

}

Any suggestions?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    drpzr64329 drpzr64329 2014-07-01 15:47

    For this specific problem I've found a solution. If you want to get the headers from the request that I sent in the question above, you can use php's get_headers($url) method. It retrieves the headers that I was looking for. I'm really new to protocols and web-services and also to php (1 or 1.5 weeks), therefore I may have asked a silly question and not have been specific enough. Anyways thank you very much for your answers.

    Have a nice day!

    点赞 评论 复制链接分享
  • dragonmeng2002 dragonmeng2002 2014-07-01 14:18

    A GET request also contains a header wich include things like the useragent oder the encoding, you should have a look at what you need to send and what's optional

    点赞 评论 复制链接分享

相关推荐