我正在使用http://dictionary.reference.com/browse/:word并检查返回的响应的状态,以评估“单词”定义是否存在。它适用于正确的单词(200状态代码)。但对于那些拼写不正确的人(404状态代码),我无法从HttpWebRequest.GetResponse()中捕获状态代码,因为它返回null?
问题是我正在使用PostMan进行检查,我确实收到了以下网址的状态码404:
http://dictionary.reference.com/browse/sdfsdsdc
这是我的实施:
string baseURL = "http://dictionary.reference.com/browse";
bool result = false;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL + "/" + word);
request.Method = "GET";
//request.Timeout = 2000;
request.KeepAlive = false;
request.ContentType = "text/html; charset=UTF-8";
Console.WriteLine(request.RequestUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode statusCode = response.StatusCode;
int statusCodeNumber = (int)statusCode;
Console.WriteLine("Status Code: " + statusCode + " - status number: " + statusCodeNumber);
try
{
if (statusCodeNumber == 200) result = true;
else if (statusCodeNumber == 404) { result = false; }
else { throw new UnknownStatusCodeException(); }
}
catch (UnknownStatusCodeException e) {}
response.Close();
}
catch (WebException e) {
}
}
这是我抓到的WebException
有人可以给我一些指示吗?感谢