首页 > 微信头像读取特别慢

微信头像读取特别慢

用浏览器打开特别快,但用程序下载的时候,头像地址:http://wx.qlogo.cn/mmopen/Q3auHgzwzM7stNZun2icoVrJ4f70z0zlyDDnRrZdlUp9...

我是用的微信公众号的测试账号。


的确和用什么工具读取有关系,curl,在参数设置合适的时候,会比较快。直接用php的file_get_contents就特别慢(php stream wrapper)。据说是浪费在了dns解析这个上面。但实践中,用curl的确要快很多。

参考相似问题:http://.com/q/1010000002638540

通过google,找到了一个比较令人信服的答案。更重要的,它提供了一个好思路:用Shark看网络包来分析问题所在。

答案如下:

I had a hard time figuring out the cause of the slowness of
file_get_contents scripts.

By analyzing it with Wireshark, the issue (in my case and probably
yours too) was that the remote web server DIDN'T CLOSE THE TCP
CONNECTION UNTIL 15 SECONDS (i.e. "keep-alive").

Indeed, file_get_contents doesn't send a "connection" HTTP header, so
the remote web server considers by default that's it's a keep-alive
connection and doesn't close the TCP stream until 15 seconds (It might
not be a standard value - depends on the server conf).

A normal browser would consider the page is fully loaded if the HTTP
payload length reaches the length specified in the response
Content-Length HTTP header. File_get_contents doesn't do this and
that's a shame.

SOLUTION

SO, if you want to know the solution, here it is:

$context = stream_context_create(array('http' =>
array('header'=>'Connection: close\r\n')));
file_get_contents("http://www.something.com/somepage.html",false,$context);
The thing is just to tell the remote web server to close the
connection when the download is complete, as file_get_contents isn't
intelligent enough to do it by itself using the response
Content-Length HTTP header.

http://stackoverflow.com/questions/3629504/php-file-get-contents-very-slow-when-using-full-url


用curl读取,秒度。
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);


在项目中建议自己构建图像服务器,这样读取缓存快一些。


慢你就把它下载下来保存到自己服务器上嘛!

【热门文章】
【热门文章】