2

次の関数を使用すると、プロキシを介していくつかの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 ステートメントに入らないのでしょうか。

4

1 に答える 1

3

おそらく、WebException 型ではない例外を返しています。太陽の下ですべての例外をキャッチするには、フォールバックとして「catch Exception」を含める必要があります

WebException キャッチの後にフォールバック キャッチを追加し、それをデバッグして、実際に返されている例外の種類を確認します。

于 2013-03-28T05:38:04.347 に答える