你的位置:首页 > 软件开发 > ASP.net > 用socket 模拟http请求

用socket 模拟http请求

发布时间:2015-06-18 00:01:07
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Thr ...
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;  class HttpHelper  {    #region 模拟客户端socket连接    private static Socket ConnectSocket(get='_blank'>string server, int port)    {      Socket s = null;      IPHostEntry hostEntry = null;      // Get host related information.      hostEntry = Dns.GetHostEntry(server);      // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid      // an exception that occurs when the host IP Address is not compatible with the address family      // (typical in the IPv6 case).      foreach (IPAddress address in hostEntry.AddressList)      {        IPEndPoint ipe = new IPEndPoint(address, port);        Socket tempSocket =        new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);        tempSocket.Connect(ipe);        if (tempSocket.Connected)        {          s = tempSocket;          break;        }        else        {          continue;        }      }      return s;    }    #endregion    #region 请求的主方法 request 是http请求的头部,可以用抓包工具获取,server可以使域名或者是ip地址,port http协议一般是80    public static string SocketSendReceive(string request, string server, int port)    {      try      {        Byte[] bytesSent = Encoding.ASCII.GetBytes(request);        Byte[] bytesReceived = new Byte[655350];        // 创建连接        Socket s = ConnectSocket(server, port);        if (s == null)          return ("Connection failed");        // 发送内容.        s.Send(bytesSent, bytesSent.Length, 0);        // Receive the server home page content.        int bytes = 0;        string page = "Default HTML page on " + server + ":\r\n";        //接受返回的内容.        do        {          bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);          page = page + Encoding.UTF8.GetString(bytesReceived, 0, bytes);        }        while (bytes > 0);        return page;      }      catch      {        return string.Empty;      }    }    #endregion  }

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:用socket 模拟http请求

关键词:http

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。