c# - C# webrequests->getresponse 抛出异常而不是返回状态码
问题描述
我正在尝试制作图像抓取工具,现在对于某些页面未指定图像,因此我想根据访问页面时收到的状态代码解析我的输出,但是当我尝试削减我的状态代码时出现异常如果找不到页面,而不是状态码,知道为什么会发生这种情况吗?
if (gameinfo != null)
if (!string.IsNullOrEmpty(gameinfo.image_uri))
try
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
// Build Uri and attempt to fetch a response.
UriBuilder uribuild = new UriBuilder(gameinfo.image_uri);
WebRequest request = WebRequest.Create(uribuild.Uri);
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
switch (response.StatusCode)
{
// Page found and valid entry.
case HttpStatusCode.OK:
using (Stream stream = client.OpenRead(uribuild.Uri))
{
Console.WriteLine(String.Format("Downloading {0}", uribuild.Uri));
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
bitmap.Save(System.IO.Path.Combine(rom_root, String.Format("{0}.jpg", file_name.Substring(2).Split('.').First())));
}
break;
// Unspecified status codes.
default:
Console.WriteLine("Unspecified status code found, aborting...");
break;
}
}
} catch(System.Net.WebException ex)
{
// Should be moved to switch with HttpStatusCode.NotFound ^
Console.WriteLine("Image page not found.");
}
解决方案
这就是GetResponse()
实现的方式。如果响应不是成功,WebException
则抛出 a。
我同意,我觉得这有点奇怪——如果它至少是可选行为就好了。值得庆幸的是,您可以从WebException
正在抛出的状态代码中读取状态代码:
....
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
var statusCode = httpResponse.StatusCode;
// Do stuff with the statusCode
}
}
推荐阅读
- regex - 无法将正则表达式模式表单文件解析为 powershell 中的变量
- android - 将布局锚定到底部工作表
- c# - C# Selenium - javascript 生成的表没有内容
- python-3.x - 如何在 AWS Lambda 中设置 PYTHONHASHSEED
- python - Azure ML 中的模型部署
- mongodb - MongoDB:使用条件更新文档字段
- clickhouse - 内部连接的 Clickhouse 传递数据
- python - 在 Dash Plotly 中添加上限/下限并更改 x 轴值格式
- flutter - 在 VS Code 终端中使用“flutter run”时,终端会自动切换到当前工作目录
- flask - 我应该如何解决为此缺少 1 个必需的位置参数错误?