使用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?

我正在尝试使用 GET code>请求发送到地址 php code>我收到 HTTP 400 BAD REQUEST code>消息,我无法弄清楚原因。 p>

这是我的代码: p> \ n

  function redirect($ url)
 {
 error_reporting(E_ERROR | E_PARSE); 
 
 $ components = parse_url($ url); 
 
 $ port = $ components [“port  “]; 
 $ ip = $ components [”host“]; 
 $ path = $ components [”path“]; 
 
 //使用用户输入的参数创建并连接套接字
 //  $ sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); 
 
 echo“建立与给定地址的连接... 
”; 
 
 
 //连接超时限制设置为10秒......  
 if(!isset($ port))
 {
 $ port = 80; 
} 
 $ sock = fsockopen($ ip,$ port,$ errno,$ errstr,10)或die(“Unable” 连接...“); 
 
 $ 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,$ 结果))
 $ loc = $ results [1]; 
 
 echo $ loc; 
 
} 
  code>  pre> 
 
 

有什么建议吗? strong> p> div>

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!

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