C#基于socket模拟http请求的方法
本文实例讲述了C#基于socket模拟http请求的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading.Tasks;
classHttpHelper
{
#region模拟客户端socket连接
privatestaticSocketConnectSocket(stringserver,intport)
{
Sockets=null;
IPHostEntryhostEntry=null;
//Gethostrelatedinformation.
hostEntry=Dns.GetHostEntry(server);
//LoopthroughtheAddressListtoobtainthesupportedAddressFamily.Thisistoavoid
//anexceptionthatoccurswhenthehostIPAddressisnotcompatiblewiththeaddressfamily
//(typicalintheIPv6case).
foreach(IPAddressaddressinhostEntry.AddressList)
{
IPEndPointipe=newIPEndPoint(address,port);
SockettempSocket=
newSocket(ipe.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
tempSocket.Connect(ipe);
if(tempSocket.Connected)
{
s=tempSocket;
break;
}
else
{
continue;
}
}
returns;
}
#endregion
#region请求的主方法request是http请求的头部,可以用抓包工具获取,server可以使域名或者是ip地址,porthttp协议一般是80
publicstaticstringSocketSendReceive(stringrequest,stringserver,intport)
{
try
{
Byte[]bytesSent=Encoding.ASCII.GetBytes(request);
Byte[]bytesReceived=newByte[655350];
//创建连接
Sockets=ConnectSocket(server,port);
if(s==null)
return("Connectionfailed");
//发送内容.
s.Send(bytesSent,bytesSent.Length,0);
//Receivetheserverhomepagecontent.
intbytes=0;
stringpage="DefaultHTMLpageon"+server+":\r\n";
//接受返回的内容.
do
{
bytes=s.Receive(bytesReceived,bytesReceived.Length,0);
page=page+Encoding.UTF8.GetString(bytesReceived,0,bytes);
}
while(bytes>0);
returnpage;
}
catch
{
returnstring.Empty;
}
}
#endregion
}
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingSystem.Reflection;
classProgram
{
publicstaticstringHeadlerInit(){
StringBuildersb=newStringBuilder();
sb.AppendLine("GEThttp://www.baidu.com/HTTP/1.1");
sb.AppendLine("Host:www.baidu.com");
sb.AppendLine("Connection:keep-alive");
sb.AppendLine("Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
sb.AppendLine("User-Agent:Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/42.0.2311.90Safari/537.36");
sb.AppendLine("Accept-Encoding:deflate,sdch");
sb.AppendLine("Accept-Language:zh-CN,zh;q=0.8");
sb.AppendLine("\r\n");
//这个一定要有不然接收回来可能没有数据
returnsb.ToString();
}
staticvoidMain(string[]args)
{
stringgetStrs=HeadlerInit();
stringgetHtml=HttpHelper.SocketSendReceive(getStrs,"www.baidu.com",80);
Console.WriteLine(getHtml);
}
}
希望本文所述对大家的C#程序设计有所帮助。