HttpListener 实现小型web服务器
程序员文章站
2022-06-21 19:55:55
HttpListener 实现web服务器 用于小型服务器,简单、方便、不需要部署。 总共代码量不超过50行。 可通过网页直接访问。 程序访问方法 JSON数据传输方法 ......
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; }
上一篇: 达令家的新国货计划,是否会成为下一个“小米有品”?
下一篇: 我们是被人雇佣