出于公司的一个需求,我要写一个下载网易微博的一个头像,但是网易微博的的图片是不允许外链的,所以我们只下载它,好了动手了,呵呵
一开始我用这样来读流
using (var stream = response.GetResponseStream())
{
//byte[] bytes = new byte[stream.Length];
//stream.Read(bytes, 0, bytes.Length);
//// 设置当前流的位置为流的开始
//stream.Seek(0, SeekOrigin.Begin);
}
{
//byte[] bytes = new byte[stream.Length];
//stream.Read(bytes, 0, bytes.Length);
//// 设置当前流的位置为流的开始
//stream.Seek(0, SeekOrigin.Begin);
}
但是提示说,Strem不支持seek ,一到strem.length就开始报错,原因就在于 一个值得探索的未知
所以只能用折中的方式来替代了
byte[] photocontent = new Byte[response.ContentLength];
stream.Read(photocontent, 0, (int)response.ContentLength );
stream.Read(photocontent, 0, (int)response.ContentLength );
需要特别注意的是//stream.Read(content, 0, (int)webreponse.ContentLength );
//只能读取到3799字节的数据,在网上查了好久,没有找到怎么回事,后来,想到了解决大文件上传显示进度问题时,用到的//HttpWorkerRequest.ReadEntityBod(),需要检测是否读取完毕,进行多次读取才可以。
代码
int readecount = 0;
while (readecount < (int)webreponse.ContentLength)
{
readecount += stream.Read(photocontent, readecount, (int)webreponse.ContentLength - readecount);
}
while (readecount < (int)webreponse.ContentLength)
{
readecount += stream.Read(photocontent, readecount, (int)webreponse.ContentLength - readecount);
}
剩下就是我下载163 的图片的全部过程了
代码
Uri uri = new Uri("http://oimagec4.ydstatic.com/image?w=48&h=48&url=http%3A%2F%2Fos.blog.163.com%2Fcommon%2Ftinyava.s%3Fhost%3Dthetimeweekly%26type%3D1%26rnd%3D0.28753444320203836");
var request = WebRequest.Create(uri) as HttpWebRequest;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Timeout = 6000;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Headers["Accept-Encoding"] = "gzip, deflate";
request.Accept = "*/*";
//request.Headers["host"] = "www.aqlife.com";
//request.Connection = "Keep-Alive";
var response = request.GetResponse() as HttpWebResponse;
using (var stream = response.GetResponseStream())
{
//var bmp = new Bitmap(stream);
//this.pictureBox1.Image = bmp;
// stream.to
byte[] photocontent = new Byte[response.ContentLength];
stream.Read(photocontent, 0, (int)response.ContentLength );
}
var request = WebRequest.Create(uri) as HttpWebRequest;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Timeout = 6000;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Headers["Accept-Encoding"] = "gzip, deflate";
request.Accept = "*/*";
//request.Headers["host"] = "www.aqlife.com";
//request.Connection = "Keep-Alive";
var response = request.GetResponse() as HttpWebResponse;
using (var stream = response.GetResponseStream())
{
//var bmp = new Bitmap(stream);
//this.pictureBox1.Image = bmp;
// stream.to
byte[] photocontent = new Byte[response.ContentLength];
stream.Read(photocontent, 0, (int)response.ContentLength );
}
欢迎大家拍砖。