写给标签

时间:2015-11-25 20:07:18

标签: c# httpwebrequest console.writeline system.net.httpwebrequest

我目前正在尝试在C#中开发一个网络抓取工具,用于测试用户指定的网页。我希望一旦爬虫启动它就会将页面状态写入窗体(包括标签)。但是我无法让程序真正写入表单?

private void button1_Click(object sender, EventArgs e)
    {
        Uri fileURI = new Uri(URLbox.Text);
        WebRequest request = WebRequest.Create(fileURI);
        HttpWebResponse response = null;

        request.Method = "HEAD";
        bool exists = false;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
            exists = response.StatusCode == HttpStatusCode.OK;

        }
        catch
        {
            exists = false;
        }
        finally
        {

            if (response != null)

                response.Close();
        }

    }
    private void label1_Click(object sender, EventArgs e)
    {
        Console.Write.ToString = ("Active");
    }

}

2 个答案:

答案 0 :(得分:1)

你真正缺少的就是在最后设置标签文字。

private void button1_Click(object sender, EventArgs e)
{
    Uri fileURI = new Uri(URLbox.Text);
    WebRequest request = WebRequest.Create(fileURI);
    HttpWebResponse response = null;

    request.Method = "HEAD";
    bool exists = false;

    try
    {
        response = (HttpWebResponse)request.GetResponse();
        exists = response.StatusCode == HttpStatusCode.OK;

    }
    catch
    {
        exists = false;
    }
    finally
    {

        if (response != null)

            response.Close();
    }

    if(exists)
    {
        label1.Text = "Active";
    }

}

答案 1 :(得分:0)

以下代码有效!

 public URLTester1()
    {
        InitializeComponent();
    }


    //Web Page Active?

    private void button1_Click(object sender, EventArgs e)
    {
        Uri fileURI = new Uri(URLbox1.Text);

        //tests http response 
        WebRequest request = WebRequest.Create(fileURI);
        HttpWebResponse response = null;

        request.Method = "HEAD";


        bool exists = false;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
            exists = response.StatusCode == HttpStatusCode.OK;

        }
        catch
        {
            exists = false;
        }
        finally
        {
            // close your response.
            if (response != null)

                response.Close();
        }

        if (exists)
        {
            label1.Text = "Active";
        }
        else
        {
            label1.Text = "Inactive";
        }