我要讓HTTP請求,而不具有依賴性,打開插座連接到捲曲和allow_url_fopen = 1
和發送原始的HTTP請求:因爲我使用HTTP/1.1如何在製作原始HTTP請求時輕鬆解碼HTTP分塊的編碼字符串?
/**
* Make HTTP GET request
*
* @param string the URL
* @param int will be filled with HTTP response status code
* @param string will be filled with HTTP response header
* @return string HTTP response body
*/
function http_get_request($url, &$http_code = '', &$res_head = '')
{
$scheme = $host = $user = $pass = $query = $fragment = '';
$path = '/';
$port = substr($url, 0, 5) == 'https' ? 443 : 80;
extract(parse_url($url));
$path .= ($query ? "?$query" : '').($fragment ? "#$fragment" : '');
$head = "GET $path HTTP/1.1\r\n"
. "Host: $host\r\n"
. "Authorization: Basic ".base64_encode("$user:$pass")."\r\n"
. "Connection: close\r\n\r\n";
$fp = fsockopen($scheme == 'https' ? "ssl://$host" : $host, $port) or
die('Cannot connect!');
fputs($fp, $head);
while(!feof($fp)) {
$res .= fgets($fp, 4096);
}
fclose($fp);
list($res_head, $res_body) = explode("\r\n\r\n", $res, 2);
list(, $http_code,) = explode(' ', $res_head, 3);
return $res_body;
}
功能工作正常,但響應正文通常在Chunked-encoded字符串中返回。例如(維基百科):
25
This is the data in the first chunk
1C
and this is the second one
3
con
8
sequence
0
我不想使用http_chunked_decode()
因爲它有PECL依賴,我想一個高度可移植的代碼。
如何輕鬆解碼HTTP分塊編碼的字符串,以便我的函數可以返回原始HTML?我還必須確保解碼字符串的長度與Content-Length:
標題匹配。
任何幫助,將不勝感激。謝謝。
【如何正確處理分塊編碼的要求嗎?(http://stackoverflow.com/questions/3289574/how-to-handle-chunked-encoding-request-properly) –
[這個問題的可能重複](http://stackoverflow.com/q/3289574/1396314)與我的問題有點相似。但選擇的答案是*太臃腫*。我正在使用那裏的代碼更簡單的解決方案。我希望這個問題不會被關閉:) – flowfree
該答案中的代碼不是那麼大,它只是很好的評論:) –