利用Socket HTTP协议获得HTML代码方法
private string GetHTML(string strURL)
{
DateTime t1 = DateTime.Now;
Uri URI = new Uri(strURL);
string strHTML = "";//用来保存获得的HTML代码
IPHostEntry gist = Dns.GetHostEntry(URI.Host);//获得当前URL的IP地址
IPAddress ip = gist.AddressList[0];//提取IP地址
IPEndPoint ipEnd = new IPEndPoint(ip, 80);//封装IP地址和端口
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化Stock
try { socket.Connect(ipEnd); }//自动循环捕捉连接
catch { }
string sendstr = string.Format("GET {1} HTTP/1.1\r\nConnection:close\r\nHost:{0}\r\n\r\n", URI.Host, URI.PathAndQuery);//定义HTTP协议头部
byte[] ms = UTF8Encoding.UTF8.GetBytes(sendstr);//将头部转换成byte形式
socket.Send(ms);//发送
int recv = -1;//定义接受数据长度
byte[] data = new byte[1024];//用来保存接收数据
do
{
recv = socket.Receive(data);
strHTML += Encoding.Default.GetString(data, 0, recv);
} while (recv!= 0);
DateTime t2 = DateTime.Now;
CeShiTime +="Socket:"+(t2 - t1).Milliseconds.ToString()+" ";
return strHTML;
}
以上代码在VS2008环境测试通过
{
DateTime t1 = DateTime.Now;
Uri URI = new Uri(strURL);
string strHTML = "";//用来保存获得的HTML代码
IPHostEntry gist = Dns.GetHostEntry(URI.Host);//获得当前URL的IP地址
IPAddress ip = gist.AddressList[0];//提取IP地址
IPEndPoint ipEnd = new IPEndPoint(ip, 80);//封装IP地址和端口
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化Stock
try { socket.Connect(ipEnd); }//自动循环捕捉连接
catch { }
string sendstr = string.Format("GET {1} HTTP/1.1\r\nConnection:close\r\nHost:{0}\r\n\r\n", URI.Host, URI.PathAndQuery);//定义HTTP协议头部
byte[] ms = UTF8Encoding.UTF8.GetBytes(sendstr);//将头部转换成byte形式
socket.Send(ms);//发送
int recv = -1;//定义接受数据长度
byte[] data = new byte[1024];//用来保存接收数据
do
{
recv = socket.Receive(data);
strHTML += Encoding.Default.GetString(data, 0, recv);
} while (recv!= 0);
DateTime t2 = DateTime.Now;
CeShiTime +="Socket:"+(t2 - t1).Milliseconds.ToString()+" ";
return strHTML;
}