【发布时间】:2015-10-06 18:47:39
【问题描述】:
我的变量 httpRes 有问题。基本上这是一个命令行应用程序的基础知识,它将检查一组给定的 URL 并返回它们的状态代码,即未经授权、重定向、正常等。问题是我列表中的一个应用程序不断抛出错误。所以我使用了 try catch 子句来捕获错误并告诉我是什么原因造成的。
不幸的是,变量 httpRes 在 try 子句中有效,但在 catch 中无效。它一直被返回为空。我在 try/catch 语句之外调用了 httpRes,所以我希望我的范围是正确的,但无论出于何种原因,catch 语句的值永远不会从 null 更改,只有 try 语句。
这里是引用的代码。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace URLMonitor
{
class Program
{
static void Main(string[] args)
{
string url1 = "https://google.com"; //removed internal URL for security reasons.
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url1);
httpReq.AllowAutoRedirect = false;
HttpWebResponse httpRes = null;
try
{
httpRes = (HttpWebResponse)httpReq.GetResponse();
if (httpRes.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("Website is OK");
// Close the response.
//httpRes.Close();
}
}
catch
{
if (httpRes != null)
{
if (httpRes.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("Things are not OK");
//httpRes.Close();
}
}
else
{
Console.WriteLine("Please check the URL and try again..");
//httpRes.Close();
}
}
Console.ReadLine();
}
}
}
【问题讨论】:
标签: c# .net httpwebrequest httpwebresponse http-error