有时变量 doc 或 type 为空。所以我尝试先添加if (type == null){....} else {....}
但如果它是 null 我应该返回什么?现在我尝试使用 try 和 catch 但由于它为空,所以我在另一个使用此类的类中得到空异常。
public static HtmlAgilityPack.HtmlDocument getHtmlDocumentWebClient(string url, bool useProxy, string proxyIp, int proxyPort, string usename, string password)
{
HtmlAgilityPack.HtmlDocument doc = null;
using (MyClient clients = new MyClient())
{
clients.HeadOnly = true;
byte[] body = clients.DownloadData(url);
// note should be 0-length
string type = clients.ResponseHeaders["content-type"];
clients.HeadOnly = false;
// check 'tis not binary... we'll use text/, but could
// check for text/html
try
{
if (type.StartsWith(@"text/html"))
{
string text = clients.DownloadString(url);
doc = new HtmlAgilityPack.HtmlDocument();
WebClient client = new WebClient();
//client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = WebRequest.DefaultWebProxy;
if (useProxy)
{
//Proxy
if (!string.IsNullOrEmpty(proxyIp))
{
WebProxy p = new WebProxy(proxyIp, proxyPort);
if (!string.IsNullOrEmpty(usename))
{
if (password == null)
password = string.Empty;
NetworkCredential nc = new NetworkCredential(usename, password);
p.Credentials = nc;
}
}
}
doc.Load(client.OpenRead(url));
}
}
catch
{
}
}
if (doc == null)
{
//MessageBox.Show("Doc is null " + doc + " The link that did it was " + url);
}
return doc;
}
该函数每次都获取 url,并且在某些特定的 url 上,变量类型为空。网站需要密码什么的原因。
我应该如何处理 null ?