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, , 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, , 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 = ;
request.ContentType = "application/json";
//request.ContentType = "text/xml; charset=utf-8";
byte[] jsonbyte = Encoding.UTF8.GetBytes(json);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, , 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;
}

最新文章

  1. iOS-证书
  2. 基于御安全APK加固的游戏反外挂方案
  3. ASP.NET Core 1.0 中使用 Swagger 生成文档
  4. windows系统命令服务安装卸载
  5. String字符串包含运算符实现运算
  6. JAVA中的各种 哈希码(HashCode) 与 equals方法在HIBERNATE的实际应用[转载]
  7. TabBarItem图片大小改变
  8. 用overflow-y 解决web页面抖动问题
  9. WINDOWS动态链接库--MFC规则动态链接库
  10. 【排序算法】归并排序算法 Java实现
  11. enumerate给列表加索引
  12. pandas和spark的dataframe互转
  13. Terraria(泰拉瑞亚)存档覆盖(Linux)
  14. 【原创】Python第一章
  15. chrome&#39;s developer console
  16. python面试一:python2与python3的区别一
  17. Linux下Maven+SVN自动打包脚本
  18. iOS开发-16进制颜色转换
  19. PCL行人检测
  20. 使用UUID方法生成全球唯一标识

热门文章

  1. python中反转列表的三种方式
  2. Java日期时间API系列2-----Jdk7及以前的日期时间类在mysql数据库中的应用
  3. FCC---Make Motion More Natural Using a Bezier Curve--- juggling movement
  4. JDK8日常开发系列:Consumer详解
  5. 访问rabbitmq-server失败
  6. BayaiM__MySQL错误对照表
  7. zsh: command not found: 解决方法
  8. appium---adb logcat 命令详解
  9. itest(爱测试) 3.5.0 发布,开源BUG 跟踪管理&amp; 敏捷测试管理软件
  10. 借助meta影藏顶部菜单