C#用SOCKET发送HTTP请求小例

private void button1_Click(object sender, EventArgs e)
        {
            string urlStr = this.textUrl.Text ;
            if (urlStr == null || "".Equals(urlStr))
            {
                MessageBox.Show( "必须填写要防问的地址!");
                return;
            }
            int port = 80;
            try
            {
                port = Convert.ToInt32(this.textPort.Text);
            }
            catch
            {
                MessageBox.Show( "请填写正确的端口");
            }
            //可以为空
            string path = "/"+this.textFile.Text;
            this.textBox1.Text = "";
            this.conn.StartAccess(urlStr, port, path, this.textBox1);
        }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
    class MyConnection
    {
        public void StartAccess( string urlStr ,int port , string path , TextBox list )
        {
            byte[] data = new byte[1024];
            IPHostEntry gist = Dns.GetHostByName( urlStr );
            //得到所访问的网址的IP地址
            IPAddress ip = gist.AddressList[0];
            IPEndPoint ipEnd = new IPEndPoint(ip, port);
            //使用tcp协议 stream类型 (IPV4)
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(ipEnd);
            }
            catch (SocketException e)
            {
                MessageBox.Show("与访问的服务器连接异常!");
                Console.Write(e.ToString());
                return;
            }
            //这里请求的相对地址,如果访问直接www.baidu.com则不需要,可以为空.
            StringBuilder buf = new StringBuilder();
            buf.Append("GET ").Append(path).Append(" HTTP/1.0/r/n");
            buf.Append("Content-Type: application/x-www-form-urlencoded/r/n");
            buf.Append("/r/n");
            byte[] ms = System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString());
            //发送
            socket.Send(ms);
            int recv =0;
           
            do
            {
                recv = socket.Receive(data);
                //如果请求的页面meta中指定了页面的encoding为gb2312则需要使用对应的Encoding来对字节进行转换
                //list.Text += (Encoding.UTF8.GetString(data, 0, recv));
                list.Text += (Encoding.Default.GetString(data, 0, recv));
            } while (recv != 0);
            //禁用上次的发送和接受
            socket.Shutdown( SocketShutdown.Both );
            socket.Close();
        }
    }
}

 

posted @ 2014-09-01 12:06  Alex.Net  阅读(2447)  评论(1编辑  收藏  举报