WebRequest.Reponse可以获取带有重定向301网址的图片 [英] WebRequest.Reponse can get Image with redirect 301 url

查看:67
本文介绍了WebRequest.Reponse可以获取带有重定向301网址的图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我正在编程一个模块下载图像,代码如下:

Hi all,
I am programming an module downloading image, the code as below:

WebRequest wr = WebRequest.Create(url);
WebResponse ws = wr.GetResponse(); // => throw exception 404 with the below url
Stream dataStream = ws.GetResponseStream();



它使用url引发异常:

http://doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG

但是它可以通过www.
与该URL一起使用. http://www.doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG

实际上,无论是否使用www,Firefox/Chrome/IE都可以在两个URL上使用.

如何像Firefox一样下载图像?
预先感谢,
TuanNM



It throw an exception with url like:

http://doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG

But it work with this url with www.
http://www.doanhnhan.net/Resources/Data/News/huyenct/th%C3%A1ng%209/24/kinh%20t%E1%BA%BF/TMDT2.JPG

In fact, Firefox/Chrome/IE work on both urls, with and without www.

How can I download the image like Firefox do?
Thank in advance,
TuanNM

推荐答案

尝试一下...赶紧找到wr.GetResponse.如果捕获到异常,请找出它是否为"404 not found".在这种情况下,请添加"www".然后重试,例如
Do a try...catch arong the wr.GetResponse. If you catch an exception, find out if it is a "404 not found". In that case, add a "www." and try again, e.g.
try
{
    System.Net.WebResponse ws = wr.GetResponse();
}
catch (System.Net.WebException wex)
{
    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("\b404\b");
    System.Text.RegularExpressions.Match match = regex.Match(wex.Message);
    if (match.Success)
    {
        //change URL
    }
}


这篇关于WebRequest.Reponse可以获取带有重定向301网址的图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆