HttpListenerServer Get Post

http://blog.csdn.net/autumn20080101/article/details/52680760

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Xml.Serialization;
using System.Threading;
using System.Web;

namespace TestHttpSrv
{
    class Program
    {
        static void Main(string[] args)
        {
            ////////////////////////////////////////////////////////
            HttpListener listener = new HttpListener();
            //using (HttpListener listener = new HttpListener())
            {
                listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//= AuthenticationSchemes.Negotiate;
                listener.Prefixes.Add("http://localhost:5555/");
                //listener.Prefixes.Add("https://localhost:8000/");
                listener.Start();
                //new Thread(new ThreadStart(delegate
                //{
                while (true)
                {
                    HttpListenerContext httpListenerContext = listener.GetContext();
                    httpListenerContext.Response.StatusCode = 200;
                    String method = httpListenerContext.Request.HttpMethod;
                    if (method.Trim().ToUpper().Equals("POST"))
                    {
                        doPost(httpListenerContext);
                    }
                    else if (method.Trim().ToUpper().Equals("GET"))
                    {
                        doGet(httpListenerContext);
                    }


                }
                listener.Stop();
                //})).Start();

                //listener.Stop();
            }
            ////////////////////////////////////////////////////////
        }

        private static void doPost(HttpListenerContext httpListenerContext)
        {
            String postValues = GetPostValues(httpListenerContext);
            Dictionary<String, String> valueDict = PostValues2Dictionary(postValues);
            string name = (valueDict != null) ? (valueDict.ContainsKey("name") ? valueDict["name"] : "noNameValue") : "noPostValue";
            StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream);
            ///////////////////////////////////////////

            writer.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>测试服务器</title></head><body>");
            writer.WriteLine("<ul>");
            writer.WriteLine(postValues);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.RawUrl);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.QueryString);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.Url);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UrlReferrer);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserAgent);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserHostAddress);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserHostName);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserLanguages);
            writer.WriteLine("</ul>");
            ///////////////////////////////////////////
            writer.WriteLine("<p>Hello, {0}</p>", name);
            writer.WriteLine("<ul>");
            foreach (string header in httpListenerContext.Request.Headers.Keys)
            {
                writer.WriteLine("<li><b>{0}:</b> {1}</li>", header, httpListenerContext.Request.Headers[header]);
            }
            writer.WriteLine("</ul>");
            writer.WriteLine("</body></html>");

            writer.Close();
            httpListenerContext.Response.Close();
        }

        private static Dictionary<string, string> PostValues2Dictionary(string postValues)
        {
            //name=jim&age=11
            if (String.IsNullOrEmpty(postValues) || String.IsNullOrEmpty(postValues.Trim()))
            {
                return null;
            }
            String[] keyValues = postValues.Trim().Split('&');
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (String key_value in keyValues)
            {
                int indexOfEqualsSign = key_value.IndexOf('=');
                string key = key_value.Substring(0, indexOfEqualsSign);
                string val = key_value.Substring(indexOfEqualsSign + 1);
                dict[key] = val;
            }
            return dict;
        }

        private static string GetPostValues(HttpListenerContext httpListenerContext)
        {
            HttpListenerRequest request = httpListenerContext.Request;
            if (!request.HasEntityBody)
            {
                return null;
            }
            using (System.IO.Stream body = request.InputStream) // here we have data
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }


        private static void doGet(HttpListenerContext httpListenerContext)
        {
            string name = httpListenerContext.Request.QueryString["name"];
            StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream);
            ///////////////////////////////////////////
            writer.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>测试服务器</title></head><body>");
            writer.WriteLine("<ul>");
            writer.WriteLine("GET");
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.RawUrl);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.QueryString);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.Url);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UrlReferrer);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserAgent);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserHostAddress);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserHostName);
            writer.WriteLine("<hr>");
            writer.WriteLine(httpListenerContext.Request.UserLanguages);
            writer.WriteLine("</ul>");
            ///////////////////////////////////////////
            writer.WriteLine("<p>Hello, {0}</p>", name);
            writer.WriteLine("<ul>");
            foreach (string header in httpListenerContext.Request.Headers.Keys)
            {
                writer.WriteLine("<li><b>{0}:</b> {1}</li>", header, httpListenerContext.Request.Headers[header]);
            }
            writer.WriteLine("</ul>");
            writer.WriteLine("</body></html>");
            writer.Close();
            httpListenerContext.Response.Close();
        }
    }
}

posted @ 2017-09-27 14:23  老豆芽  阅读(660)  评论(0)    收藏  举报