0

所以我目前正在尝试实现广泛用于“GET”和“POST”程序的“SendToHost”功能。就我而言,我想用它来向购物网站的邮政编码输入表单发送“邮政编码”,以用于检索该邮政编码的特定目录。更具体地说,代码应自动生成包含邮政编码结果的网页。下面是我的代码加上函数,我想知道它为什么不起作用:

function SendToHost($host, $method, $path, $data, $useragent=0)
{
  // Supply a default method of GET if the one passed was empty
  if (empty($method))
    $method = 'GET';
  $method = strtoupper($method);
  $fp = fsockopen($host,80);
  if ($method == 'GET')
    $path .= '?' . $data;
  fputs($fp, "$method $path HTTP/1.1\n");
  fputs($fp, "Host: $host\n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
  fputs($fp, "Content-length: " . strlen($data) . "\n");
  if ($useragent)
    fputs($fp, "User-Agent: MSIE\n");
  fputs($fp, "Connection: close\n\n");
  if ($method == 'POST')
    fputs($fp, $data);

  while (!feof($fp))
    $buf .= fgets($fp,128);
  fclose($fp);
  return $buf;
}

echo sendToHost('catalog.coles.com.au','get','/default.aspx','ctl00_Body_PostcodeTextBox=4122');
4

1 回答 1

1

您在标题中使用了错误的换行样式。你需要使用\r\n,而不仅仅是\n

来自 HTTP/1.1 文档的引用:

HTTP/1.1 将序列 CR LF 定义为除实体主体之外的所有协议元素的行尾标记

来源:http ://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2


如果您只是发送简单的 POST/GET 请求,我建议您使用像cURL这样的 HTTP 库。除非您正在做更复杂的事情,否则没有理由手动打开套接字并发送标头。

function SendToHost($url, $data, $method='GET', $useragent=FALSE){
    $ch = curl_init();
    $options = array(
        CURLOPT_RETURNTRANSFER => TRUE
    );

    if($method === 'POST'){
        $options += array(
            CURLOPT_URL => $url,
            CURLOPT_POST => TRUE,
            // Passing a string will set `application/x-www-form-urlencoded`
            // Whereas an array will set `multipart/form-data`
            CURLOPT_POSTFIELDS => http_build_query($data)
        );
    }
    elseif($method === 'GET'){
        $options[CURLOPT_URL] = $url . '?' . http_build_query($data);
    }

    if($useragent){
        $options[CURLOPT_USERAGENT] = 'MSIE';
    }

    curl_setopt_array($ch, $options);        
    $buf = curl_exec($ch);        
    curl_close($ch);        
    return $buf;
}

您对它的称呼略有不同:

echo sendToHost('http://catalog.coles.com.au/default.aspx', array(
    'ctl00_Body_PostcodeTextBox' => 4122
));

哎呀,如果您只想发送 GET 请求,您甚至可以使用file_get_contents

echo file_get_contents('http://catalog.coles.com.au/default.aspx?ctl00_Body_PostcodeTextBox=4122');
于 2013-09-18T18:05:51.077 回答