使用WebRequest.GetResponse下载图像时出现异常 - 如何? [英] Exception when download image using WebRequest.GetResponse - How?

查看:81
本文介绍了使用WebRequest.GetResponse下载图像时出现异常 - 如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在编写一个从互联网上下载图像的模块。

我使用的代码如下:



 WebRequest wr = WebRequest.Create(url); 
WebResponse ws = wr.GetResponse(); // =>抛出异常
流dataStream = ws.GetResponseStream();





但是,有一些例外,我不知道如何解决:



Url 1:http://dtgroup.com.vn/uploads/news/2011_08/ipd1311237144.gif

=> ;抛出异常:服务器提交了协议违规。 Section = ResponseHeader Detail =标题名称无效



Url 2:http://cocdoc.fpt.edu.vn/sites/default/files/ imagecache / 318x191 / anhtin / 2_3.JPG

=>抛出异常:远程服务器返回错误:(403)禁止。



事实上,这两个url都适用于Firefox / Chrome,但我的程序无法下载它们。



你能告诉我一些指南。

非常感谢。

TuanNM

解决方案

某些服务器检查有效的referer。由于您可以直接使用Firefox访问图像,因此不包括在内。

另一个想法是用户代理。尝试在你的应用程序中将它设置为Firefox(找出正确的措辞!),也许这会有所帮助。


尝试将此代码放入app或web.config文件中:



 <   system.net  >  
< 设置 >
< httpWebRequest useUnsafeHeaderParsing = true / >
< / settings >
< / system.net >


Hi all,
I am programing a module which download images from internet.
I am using code as below:

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



But, there are some exception that I dont know how to resolve:

Url 1: http://dtgroup.com.vn/uploads/news/2011_08/ipd1311237144.gif
=> throw exception: The server committed a protocol violation. Section=ResponseHeader Detail=Header name is invalid

Url 2: http://cocdoc.fpt.edu.vn/sites/default/files/imagecache/318x191/anhtin/2_3.JPG
=> throw exception: The remote server returned an error: (403) Forbidden.

Infact, both url work on Firefox/Chrome, but my program cant download them.

Could you please show me some guides.
Thanks so much.
TuanNM

解决方案

Some servers check for a valid "referer". Since you can access the images directly with Firefox, that is excluded.
Another idea is the "user agent". Try to set it in your application to Firefox (find out the correct wording!), perhaps that helps.


Try putting this code in your app or web.config file :

<system.net>
    <settings>
        <httpWebRequest useUnsafeHeaderParsing="true" />
    </settings>
</system.net>


这篇关于使用WebRequest.GetResponse下载图像时出现异常 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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