从互联网上获取HTML来源遇到一些问题

时间:2014-11-20 15:12:36

标签: c#

我想获取一个网页来分析股票信息。我使用以下示例代码来使用c#获取html数据。在编译时,运行它总是以错误结束。

enter image description here

以下是我的示例代码:

string urlAddress = "http://pchome.syspower.com.tw/stock/sto0/ock2/sid2404.html";
var request = (HttpWebRequest)WebRequest.Create(urlAddress);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 1414;
var requestStream = request.GetRequestStream();
requestStream.Write(Encoding.UTF8.GetBytes("is_check=1"), 0, 10);
requestStream.Close();
var response = (HttpWebResponse)request.GetResponse();
var sr = new StreamReader(response.GetResponseStream());
string rawData = sr.ReadToEnd();
sr.Close();
response.Close();

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

错误主要与您的代码顺序以及您仍将使用的Stream个对象的关闭有关。

另外,我建议尽可能使用using来正确处理对象。

使用此代码:

string rawData;
byte[] bytes = Encoding.UTF8.GetBytes("is_check=1");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;

using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(bytes, 0, bytes.Length);

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            rawData = sr.ReadToEnd();
        }
    }
}