[C#.NET][TCP Socket] 使用 HttpWebRequest 与 HttpWebResponse 类取得服务器串流

[C#.NET][TCP Socket] 使用 HttpWebRequest 与 HttpWebResponse 类取得服务器串流


续上篇 [NetWork] 使用 HttpWebRequest 与 HttpWebResponse 类取得服务器资讯,本篇则是实践GetResponseStream(),用来取得网页数据。

程序的流程都相同。


实践范例码如下:
private void button1_Click(object sender, EventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox1.Text);
    request.Method = WebRequestMethods.Http.Get;
    HttpWebResponse response = null;
    Stream stream = null;
    StreamReader streamReader = null;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode==HttpStatusCode.OK)
        {
            stream = response.GetResponseStream();
            streamReader = new StreamReader(stream);
            char[] buffer = new char[256];
            int data = 0;
            string result = "";
            //分批读
            while (true)
            {
                data = streamReader.Read(buffer, 0, buffer.Length);
                string msg = new string(buffer, 0, data);
                result = result + msg;
                if (data == 0)
                    break;
            }
            txtResponse.Text = result; 
        }
    }
    catch (WebException ex1)
    {
        HttpWebResponse exResponse = (HttpWebResponse)ex1.Response;
        MessageBox.Show(ex1.Message);
    }
    catch (NotSupportedException ex2)
    {
        MessageBox.Show(ex2.Message);
    }
    catch (ProtocolViolationException ex3)
    {
        MessageBox.Show(ex3.Message);
    }
    catch (InvalidOperationException ex4)
    {
        MessageBox.Show(ex4.Message);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (response != null) response.Close();
        if (streamReader != null) streamReader.Close();
        if (stream != null) stream.Close();
    }
}

image


接下来采用异步方法来处理

private void button2_Click(object sender, EventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(textBox1.Text);
    request.Method = WebRequestMethods.Http.Get;
    request.BeginGetResponse(new AsyncCallback(responseCallback), request);
}
void responseCallback(IAsyncResult Result)
{
    HttpWebRequest request = Result.AsyncState as HttpWebRequest;
    HttpWebResponse response = request.EndGetResponse(Result) as HttpWebResponse;//取得串流数据
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream stream = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(stream);
        char[] buffer = new char[256];
        int data = 0;
        string result = "";
        //分批读
        while (true)
        {
            data = streamReader.Read(buffer, 0, buffer.Length);
            string msg = new string(buffer, 0, data);
            result = result + msg;
            if (data == 0)
                break;
        }
        this.BeginInvoke(new updateControl(UpdateControl), new object[] { txtResponse, result });
        //txtResponse.Text = result;
    }
}
delegate void updateControl(Control Ctrl, string Msg);
void UpdateControl(Control Ctrl, string Msg)
{
    ((TextBox)Ctrl).Text = Msg;
}

执行结果仍与上图相同,这次就懒的抓例外。


后记:HttpWebResponseStream.zip

每一个网站类型都不太一样,若是不同的网站,程序分析的流程也会有所不同,所以若遇到错误,就得多花点精神调试了。

若有谬误,烦请告知,新手发帖请多包涵

2010~2017 C# 第四季