码迷,mamicode.com
首页 > 其他好文 > 详细

动态获取页面参数内容

时间:2015-07-19 17:55:50      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

本文章主要内容为动态的获取页面内容,在地址栏后面输入参数进行相加,最终将结果返回给用户,如:

http://i.cnblogs.com/add?i=1&j=2,?前面的为处理程序路径,?后面的为请求的参数,以&分割多个参数,注意这是HTTP协议格式,一种规范,一种标准

static void Main(string[] args)
{
    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8888));
    serverSocket.Listen(10);
    while (true)
    {
        Console.WriteLine("等着请求");
        Socket socket = serverSocket.Accept();
        Console.WriteLine("来了请求了");
        string firstline;
        using (NetworkStream stream = new NetworkStream(socket))
        using (StreamReader reader = new StreamReader(stream))
        {
            firstline = reader.ReadLine();//读取GET /1.html HTTP/1.1
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
                if (line.Length <= 0)
                {
                    break;
                }
            }
        }

        string[] strs = firstline.Split( );
        string url = strs[1];//1.html
        string[] strs2 = url.Split(?);//add?i=1&j=2
        string fileAction = strs[0];//add
        string qs = strs2[1];
        Dictionary<string, string> dic = ParseQureyString(qs);
        int i = Convert.ToInt32(dic["i"]);
        int j = Convert.ToInt32(dic["j"]);

        using (NetworkStream stream = new NetworkStream(socket))
        using (StreamWriter write = new StreamWriter(stream))
        {
            write.WriteLine("HTTP/1.1 200 OK");
            write.WriteLine();
            write.WriteLine(i + j);
        }
        socket.Disconnect(false);
    }
}
/// <summary>
/// 把i=1&j=2转换为一个Dictionary
/// </summary>
/// <param name="qs"></param>
/// <returns></returns>
private static Dictionary<string, string> ParseQureyString(string qs)
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    string[] strs = qs.Split(&);
    foreach (string str in strs)
    {
        string[] kv = str.Split(=);
        string name = kv[0];
        string value = kv[1];
        dic.Add(name, value);
    }
    return dic;
}

 

判断用户名和密码,把结果返回给客户端

/login?username=admin&password=123 

动态获取页面参数内容

标签:

原文地址:http://www.cnblogs.com/genesis/p/4658784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!