変数 doc または type が null の場合があります。だから私は最初に追加しようとしましたif (type == null){....} else {....}
しかし、それが null の場合、何を返す必要がありますか? 今、try と catch を使用しようとしましたが、null であるため、このクラスを使用している別のクラスで null 例外が発生します。
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です。サイトがパスワードか何かを必要とする理由。
null をどのように処理すればよいですか?