次の関数を使用すると、プロキシを介していくつかのWebサイトのhtmlソースを取得できます。サーバーが503(サーバーが利用できない)を返す場合や、catchステートメントに入らないその他の例外を除いて、正常に動作します。
catch ステートメントでは、4 回試行した後もリクエストが失敗し続ける場合、関数は再帰的に最大 4 回呼び出されると想定され、null が返されます。
private static string GetPageHTML(string link,bool useprx)
{
int tryCount = 0;
WebClient client = new WebClient() { Proxy = new WebProxy(ProxyManager.GetProxy()) { Credentials = new NetworkCredential("xx", "xx") } };
try
{
return client.DownloadString(link);
}
catch (WebException ex)
{
var statuscode = ((HttpWebResponse)ex.Response).StatusCode;
{
if (tryCount == 3)
{
return null;
}
switch (statuscode)
{
case (HttpStatusCode.Forbidden):
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
case (HttpStatusCode.NotFound):
return null;
case (HttpStatusCode.GatewayTimeout):
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
case (HttpStatusCode.ServiceUnavailable) :
tryCount++;
System.Threading.Thread.Sleep(5000);
return GetPageHTML(link, useprx);
default: return null;
}
}
}
}
では、なぜ catch ステートメントに入らないのでしょうか。