无法忽略404找不到httpwebrequest

时间:2014-08-25 18:28:08

标签: c#

我似乎无法忽略未找到的404。

我尝试将其添加到文本文件中,以便我可以继续处理请求,但程序才会关闭。

private static readonly Thread Awesome = new Thread(Request);

private const string Url = "http://whatever/";

public static void Request() {
    try {

        const string filename = "names.txt";
        Reader.Readtext(filename);

        foreach (var names in Reader.Lastname) {

            var request = (HttpWebRequest) WebRequest.Create(Url + names);
            Console.WriteLine("Request Sent: " + Url + names);

            var response = (HttpWebResponse) request.GetResponse();
            var sr = new System.IO.StreamReader(response.GetResponseStream());

            sr.ReadToEnd();
        }

    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            var resp = ex.Response as HttpWebResponse;
            if (resp != null && resp.StatusCode == HttpStatusCode.NotFound)
            {
                const string filename = "error.txt";
                Writer.writetofile(filename, resp.ToString());
            }
        }
    }
}

private static void Main()
{

    Awesome.Start();
}

1 个答案:

答案 0 :(得分:0)

private static readonly Thread Awesome = new Thread(Request);

private const string Url = "http://whatever/";

public static void Request() {
        const string filename = "names.txt";
        Reader.Readtext(filename);

        foreach (var names in Reader.Lastname) {

            var request = (HttpWebRequest) WebRequest.Create(Url + names);
            Console.WriteLine("Request Sent: " + Url + names);
            try{
                var response = (HttpWebResponse) request.GetResponse();
                var sr = new System.IO.StreamReader(response.GetResponseStream());

                sr.ReadToEnd();            
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    var resp = ex.Response as HttpWebResponse;
                    if (resp != null && resp.StatusCode == HttpStatusCode.NotFound)
                    {
                        const string filename = "error.txt";
                        Writer.writetofile(filename, resp.ToString());
                    }
                }
            }
        }
}

private static void Main()
{

    Awesome.Start();
}