现在的位置: 首页 > 综合 > 正文

C#的一些小程序!

2014年09月05日 ⁄ 综合 ⁄ 共 2234字 ⁄ 字号 评论关闭

  1 class loginwp

  2 {

  3 public string PostData(string postURL, string postString, string encoding)

  4 {

  5 string strHTML = "";//用来保存获得的HTML代码

  6 Uri URI = new Uri(postURL);

  7 string sendString;

  8 sendString = "POST {0} HTTP/1.1\r\n";

  9 sendString += "Host: {1}\r\n";

  10 sendString += "User-Agent:Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0\r\n";

  11 sendString += "Content-Type:application/x-www-form-urlencoded\r\n";

  12 sendString += "Content-Length:{2}\r\n";

  13 sendString += "Connection:close\r\n";

  14 sendString += "Cookie:wordpress_test_cookie=WP+Cookie+check\r\n\r\n";

  15 sendString += "{3}\r\n";

  16 sendString = string.Format(sendString, URI.PathAndQuery, URI.Host, postString.Length, postString);

  17 Byte[] ByteGet = Encoding.GetEncoding(encoding)。GetBytes(sendString);

  18 IPAddress hostadd = Dns.GetHostEntry(URI.Host)。AddressList[0];

  19 IPEndPoint EPhost = new IPEndPoint(hostadd, 80);

  20 Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  21 s.Connect(EPhost);

  22 if (!s.Connected)

  23 {

  24 strHTML = "链接主机失败";

  25 }

  26 s.Send(ByteGet, ByteGet.Length, SocketFlags.None);

  27 strHTML = Recv(s, Encoding.GetEncoding(encoding));

  28 return strHTML;

  29 }

  30

  31 public static String Recv(Socket sock, Encoding encode)

  32 {

  33 Byte[] buffer = new Byte[1024];

  34 StringBuilder sb = new StringBuilder();

  35

  36 Thread.Sleep(50);//根据页面响应时间进行微调

  37 Int32 len = sock.Receive(buffer);

  38 sb.Append(encode.GetString(buffer, 0, len));

  39

  40 while (sock.Available > 0)

  41 {

  42 Thread.Sleep(300);//也可以视情况微调

  43 Array.Clear(buffer, 0, buffer.Length);

  44 len = sock.Receive(buffer);

  45 sb.Append(encode.GetString(buffer, 0, len));

  46 string ss = encode.GetString(buffer, 0, len);

  47 }

  48 sock.Close();

  49 return sb.ToString();

  50 }

  51

  52 ///

  53 /// 从返回的源代码中提取cookies 以及301或302跳转

  54 ///

  55 ///

  56 ///

  57 ///

  58 public string GetCookies(string html, out string location)

  59 {

  60 StringBuilder sbCookies = new StringBuilder();

  61 location = string.Empty;

  62 string[] arr = html.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

  63 foreach (string str in arr)

  64 {

  65 if (str.StartsWith("Set-Cookie: "))

  66 {

  67 int intStart = str.IndexOf(";");

  68 string strCookie = str.Substring(12, intStart - 11);

  69 sbCookies.Append(strCookie);

  70 }

  71 if (str.StartsWith("Location:"))

  72 {

  73 location = str.Substring(10);

  74 }

  75 }

抱歉!评论已关闭.