public string getPageFromURL(string url)
{
string content = "";
// Create a new HttpWebRequest object.Make sure that
// a default proxy is set if you are behind a fure wall.
//其中,HttpWebRequest实例不使用HttpWebRequest的构造函数来创建,二是使用WebRequest的Create方法来创建.
HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(url);
//不维持与服务器的请求状态
myHttpWebRequest1.KeepAlive = false;
//创建一个HttpWebRequest对象
//Assign the response object of HttpWebRequest to a HttpWebResponse variable./
HttpWebResponse myHttpWebResponse1;
try
{
//根据微软MSDN上所说:"决不要直接创建HttpWebResponse的实例,要使用HttpWebRequest的GetResponse()方法返回的实例."具体的原因我也不清楚,可能HttpWebResponse类的构造函数中没有实现HttpWebResponse实例的代码吧.
myHttpWebResponse1 = (HttpWebResponse)myHttpWebRequest1.GetResponse();
//设置页面的编码模式
System.Text.Encoding utf8 = System.Text.Encoding.Default;
Stream streamResponse = myHttpWebResponse1.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse, utf8);
Char[] readBuff = new Char[256];
//这里使用了StreamReader的Read()方法,参数意指从0开始读取256个char到readByff中.
//Read()方法返回值为指定的字符串数组,当达到文件或流的末尾使,方法返回0
int count = streamRead.Read(readBuff, 0, 256);
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
content += outputData;
count = streamRead.Read(readBuff, 0, 256);
}
myHttpWebResponse1.Close();
return (content);
}
catch (WebException ex)
{
content = "在请求URL为:" + url + "的页面时产生错误,错误信息为" + ex.ToString();
return (content);
}
}
{
string content = "";
// Create a new HttpWebRequest object.Make sure that
// a default proxy is set if you are behind a fure wall.
//其中,HttpWebRequest实例不使用HttpWebRequest的构造函数来创建,二是使用WebRequest的Create方法来创建.
HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(url);
//不维持与服务器的请求状态
myHttpWebRequest1.KeepAlive = false;
//创建一个HttpWebRequest对象
//Assign the response object of HttpWebRequest to a HttpWebResponse variable./
HttpWebResponse myHttpWebResponse1;
try
{
//根据微软MSDN上所说:"决不要直接创建HttpWebResponse的实例,要使用HttpWebRequest的GetResponse()方法返回的实例."具体的原因我也不清楚,可能HttpWebResponse类的构造函数中没有实现HttpWebResponse实例的代码吧.
myHttpWebResponse1 = (HttpWebResponse)myHttpWebRequest1.GetResponse();
//设置页面的编码模式
System.Text.Encoding utf8 = System.Text.Encoding.Default;
Stream streamResponse = myHttpWebResponse1.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse, utf8);
Char[] readBuff = new Char[256];
//这里使用了StreamReader的Read()方法,参数意指从0开始读取256个char到readByff中.
//Read()方法返回值为指定的字符串数组,当达到文件或流的末尾使,方法返回0
int count = streamRead.Read(readBuff, 0, 256);
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
content += outputData;
count = streamRead.Read(readBuff, 0, 256);
}
myHttpWebResponse1.Close();
return (content);
}
catch (WebException ex)
{
content = "在请求URL为:" + url + "的页面时产生错误,错误信息为" + ex.ToString();
return (content);
}
}