HttpListener 實現web服務器
用於小型服務器,簡單、方便、不需要部署。
總共代碼量不超過50行。
static void Main(string[] args) { //創建HTTP監聽 using (var httpListener = new HttpListener()) { //監聽的路徑 httpListener.Prefixes.Add("http://localhost:8820/"); //設置匿名訪問 httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; //開始監聽 httpListener.Start(); Console.WriteLine("監聽端口:8820..."); while (true) { //等待傳入的請求接受到請求時返回,它將阻塞線程,直到請求到達 var context = httpListener.GetContext(); //取得請求的對象 HttpListenerRequest request = context.Request; Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl); var reader = new StreamReader(request.InputStream); var msg = reader.ReadToEnd();//讀取傳過來的信息 //Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes)); //Console.WriteLine("Accept-Language: {0}", // string.Join(",", request.UserLanguages)); Console.WriteLine("User-Agent: {0}", request.UserAgent); Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]); Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" : "close"); Console.WriteLine("Host: {0}", request.UserHostName); Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]); // 取得回應對象 HttpListenerResponse response = context.Response; // 設置回應頭部內容,長度,編碼 response.ContentEncoding = Encoding.UTF8; //response.ContentType = "text/plain;charset=utf-8"; //var path = @"C:\Users\wyl\Desktop\cese\"; ////訪問的文件名 //var fileName = request.Url.LocalPath; //讀取文件內容 //var buff = File.ReadAllBytes(path + fileName); //response.ContentLength64 = buff.Length; //------------------------- //byte[] data = new byte[1] { 1 }; //StringWriter sw = new StringWriter(); //XmlSerializer xm = new XmlSerializer(data.GetType()); //xm.Serialize(sw, data); //var buff = Encoding.UTF8.GetBytes(sw.ToString()); //------------------------ //------------------------------- //構造soap請求信息 //response.ContentType = "text/xml; charset=utf-8"; //StringBuilder soap = new StringBuilder(); //soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); //soap.Append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"); //soap.Append("<soap:Body>"); //soap.Append("<GetIPCountryAndLocal xmlns=\"http://tempuri.org/\">"); //soap.Append("<RequestIP>183.39.119.90</RequestIP>"); //soap.Append("</GetIPCountryAndLocal>"); //soap.Append("</soap:Body>"); //soap.Append("</soap:Envelope>"); //byte[] buff = Encoding.UTF8.GetBytes(soap.ToString()); //----------------------------------- response.ContentType = "text/xml; charset=utf-8"; string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now); byte[] buff = Encoding.UTF8.GetBytes(responseString); // 輸出回應內容 System.IO.Stream output = response.OutputStream; output.Write(buff, 0, buff.Length); // 必須關閉輸出流 output.Close(); } } }
可通過網頁直接訪問。
程序訪問方法
string httpUrl = System.Configuration.ConfigurationManager.AppSettings["url"];// http://localhost:8820/ WebRequest webRequest = WebRequest.Create(httpUrl); webRequest.ContentType = "text/xml; charset=utf-8"; webRequest.Method = "POST"; string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now); //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); using (Stream requestStream = webRequest.GetRequestStream()) { byte[] paramBytes = Encoding.UTF8.GetBytes(responseString); requestStream.Write(paramBytes, 0, paramBytes.Length); } //響應 WebResponse webResponse = webRequest.GetResponse(); using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)) { string result = ""; result = myStreamReader.ReadToEnd(); }
JSON數據傳輸方法
//data未數據對象 string str = JsonConvert.SerializeObject(data); string res = Post(httpUrl, str); public static string Post(string url, string json) { string st; try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //創建請求 CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.Method = "POST"; //請求方式為post request.AllowAutoRedirect = true; request.MaximumResponseHeadersLength = 1024; request.ContentType = "application/json"; //request.ContentType = "text/xml; charset=utf-8"; byte[] jsonbyte = Encoding.UTF8.GetBytes(json); Stream postStream = request.GetRequestStream(); postStream.Write(jsonbyte, 0, jsonbyte.Length); postStream.Close(); //發送請求並獲取相應回應數據 HttpWebResponse res = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); st = sr.ReadToEnd(); } catch (WebException ex) { //Log4netHelper.WriteErrorLog(url, ex); st = null; } return st; }