dotnet 实现对http访问的请求及应答,最好能自定义端口号,不用webservice

时间:2022-07-31 02:52:58
dotnet 实现对http访问的请求及应答,最好能自定义端口号,不用webservice
winform能实现吗?还是要做web程序才能实现?
请给出demo或是参考文档

12 个解决方案

#1


GOOGLE或者BAIDU,关键字CGI

#2


Common Gateway Interface

#3


除了这种方式,还有其他的方式吗?

#4


啥意思麻 dotnet 实现对http访问的请求及应答,最好能自定义端口号,不用webservice

#6


我也贴过一个最简单的例子: http://bbs.csdn.net/topics/390963758

#7


给你把这个demo修改一下,贴一个完整的console程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        private static HttpListener listener;

        static void Main(string[] args)
        {
            if (listener == null)
            {
                listener = new HttpListener();
                var url = "http://+:9876/";
                listener.Prefixes.Add(url);
                listener.Start();
                listener.BeginGetContext(MainProcess, null);
                dic.Add("abcd", test3);
                dic.Add("ef", test2);
                dic.Add("12", test1);
                Console.ReadKey();
            };
        }

        private static void MainProcess(IAsyncResult ar)
        {
            var context = listener.EndGetContext(ar);
            listener.BeginGetContext(MainProcess, null);
            var response = context.Response;
            response.AddHeader("Server", "My Server V0.0.1");
            var request = context.Request;
            var path = request.Url.LocalPath;
            if (path.StartsWith("/") || path.StartsWith("\\"))
                path = path.Substring(1);
            var visit = path.Split(new char[] { '/', '\\' }, 2);
            if (visit.Length > 0)
            {
                var cmd = visit[0].ToLower();
                Action<HttpListenerContext, string[]> actor;
                if (dic.TryGetValue(cmd, out actor))
                    actor(context, visit);
            }
        }

        private static Dictionary<string, Action<HttpListenerContext, string[]>> dic = new Dictionary<string, Action<HttpListenerContext, string[]>>();

        private static void test1(HttpListenerContext context, string[] path)
        {
            var hd = context.Request.Headers;
            var result = from x in hd.AllKeys
                         select "<p><span class='key'>" + x + "</span><span class='val'>" + hd[x] + "</span></p>";
            using (var wt = new StreamWriter(context.Response.OutputStream))
                wt.Write(string.Join("", result));
        }

        private static void test2(HttpListenerContext context, string[] path)
        {
            context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
            context.Response.Close();
        }

        private static void test3(HttpListenerContext context, string[] path)
        {
            var sb = new StringBuilder("输入请求:");
            sb.AppendLine(context.Request.Url.LocalPath);
            sb.AppendLine(string.Format("执行命令:{0}", path[0]));
            sb.AppendLine(string.Format("另外有{0}个参数", path.Length - 1 + context.Request.QueryString.Count));
            sb.AppendLine(DateTime.Now.ToString());
            context.Response.ContentType = "text/plain;charset=UTF-8";
            var result = Encoding.UTF8.GetBytes(sb.ToString());
            using (var stream = context.Response.OutputStream)
            {
                stream.Write(result, 0, result.Length);
            }
        }
    }
}



http://localhost:9876/abcd/aa.jsp?p=oooo&d=kslasdfdfs
http://localhost:9876/ef/
http://localhost:9876/12/

#8


HttpListener 

Socket

#9


注意,在win7以上操作系统,服务程序都需要“以管理员身份”启动。开发时,你的vs需要以管理员身份启动。

#10


好像就是那个httplistener

#11


http自服务,其实是相当容易的。一个.net程序设计师,就应该这种开发服务器程序的能力。不论是你的客户端是网页javascript富客户端应用程序,还是什么别的平台的程序,你懒得编写什么tcp程序的时候,编写HttpListener程序也是可以提供服务的。比如说你可以让客户端使用
new WebClient().UploadData(url, datas);
上传数据,然后在你的winfrom程序中通过
context.Request.InputStream
获取到datas数据。而且你也可以看到,技术上并不复杂,缺少的就是实践。

如果你仅仅热衷于把时间都用在跑到网上下载什么框架,你可能耽误宝贵的好几年时间。从现在开始,学会自己编写框架程序吧!

#12



        public bool RequestLoginInput()
        {
            bool retval = true;

            string sServerUrl = @"http://XX.XX.XX.XX/login.jsp";
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sServerUrl);

            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = 0;
            string ResponseStr;
            req.AllowAutoRedirect = false;
            req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
            req.KeepAlive = true;
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
            req.ContentType = "application/x-www-form-urlencoded";
            try
            {
                using (HttpWebResponse wr = (HttpWebResponse)req.GetResponse())
                {
                    Stream ResStream = wr.GetResponseStream();
                    string tempString = null;
                    int count = 0;
                    byte[] buf = new byte[8192];
                    StringBuilder sb = new StringBuilder();

                    do
                    {
                        // fill the buffer with data
                        count = ResStream.Read(buf, 0, buf.Length);

                        // make sure we read some data
                        if (count != 0)
                        {
                            // translate from bytes to ASCII text
                            tempString = Encoding.UTF8.GetString(buf, 0, count);

                            // continue building the string
                            sb.Append(tempString);
                        }
                    } while (count > 0); // any more data to read?
                    ResponseStr = sb.ToString();
                }

                object[] oPageText = { ResponseStr };
                HTMLDocument document = new HTMLDocumentClass();
                IHTMLDocument2 doc = (IHTMLDocument2)document;
                try
                {
                    string strResponse = ResponseStr;
                    doc.write(oPageText);
                    if (null != document)
                    {
                    }
                }
                catch 
                {
                }

                mshtml.HTMLDocumentClass logindocument = (mshtml.HTMLDocumentClass)document;
                mshtml.HTMLFormElement loginform = (mshtml.HTMLFormElement)logindocument.getElementById("loginform");
                mshtml.HTMLInputElement username = (mshtml.HTMLInputElement)logindocument.getElementById("username");
                mshtml.HTMLInputElement textPassword = (mshtml.HTMLInputElement)logindocument.getElementById("password");
                mshtml.HTMLInputElement rememberpwd = (mshtml.HTMLInputElement)logindocument.getElementById("savepwd");

                mshtml.HTMLInputElement localArea = (mshtml.HTMLInputElement)logindocument.getElementById("localArea");
                mshtml.HTMLInputElement localNeedAuthId = (mshtml.HTMLInputElement)logindocument.getElementById("localNeedAuthId");
                mshtml.HTMLInputElement roamNeedAuthID = (mshtml.HTMLInputElement)logindocument.getElementById("roamNeedAuthID");
                mshtml.HTMLInputElement allowNumber = (mshtml.HTMLInputElement)logindocument.getElementById("allowNumber");
                mshtml.HTMLSelectElement userOpenAddress = (mshtml.HTMLSelectElement)logindocument.getElementById("userOpenAddress");
                mshtml.HTMLInputElement passwordType = (mshtml.HTMLInputElement)logindocument.getElementById("passwordType");

                LocalArea = localArea.value;
                LocalNeedAuthId = localNeedAuthId.value;
                RoamNeedAuthID = roamNeedAuthID.value;
                AllowNumber = allowNumber.value;
                Username = Properties.Settings.Default.username;
                UserOpenAddress = userOpenAddress.value;
                Password = Properties.Settings.Default.password;
                PasswordType = passwordType.value;

            }
            catch
            {
                retval = false;
            }
            finally
            {
            }
            return retval;
        }

#1


GOOGLE或者BAIDU,关键字CGI

#2


Common Gateway Interface

#3


除了这种方式,还有其他的方式吗?

#4


啥意思麻 dotnet 实现对http访问的请求及应答,最好能自定义端口号,不用webservice

#5


#6


我也贴过一个最简单的例子: http://bbs.csdn.net/topics/390963758

#7


给你把这个demo修改一下,贴一个完整的console程序:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        private static HttpListener listener;

        static void Main(string[] args)
        {
            if (listener == null)
            {
                listener = new HttpListener();
                var url = "http://+:9876/";
                listener.Prefixes.Add(url);
                listener.Start();
                listener.BeginGetContext(MainProcess, null);
                dic.Add("abcd", test3);
                dic.Add("ef", test2);
                dic.Add("12", test1);
                Console.ReadKey();
            };
        }

        private static void MainProcess(IAsyncResult ar)
        {
            var context = listener.EndGetContext(ar);
            listener.BeginGetContext(MainProcess, null);
            var response = context.Response;
            response.AddHeader("Server", "My Server V0.0.1");
            var request = context.Request;
            var path = request.Url.LocalPath;
            if (path.StartsWith("/") || path.StartsWith("\\"))
                path = path.Substring(1);
            var visit = path.Split(new char[] { '/', '\\' }, 2);
            if (visit.Length > 0)
            {
                var cmd = visit[0].ToLower();
                Action<HttpListenerContext, string[]> actor;
                if (dic.TryGetValue(cmd, out actor))
                    actor(context, visit);
            }
        }

        private static Dictionary<string, Action<HttpListenerContext, string[]>> dic = new Dictionary<string, Action<HttpListenerContext, string[]>>();

        private static void test1(HttpListenerContext context, string[] path)
        {
            var hd = context.Request.Headers;
            var result = from x in hd.AllKeys
                         select "<p><span class='key'>" + x + "</span><span class='val'>" + hd[x] + "</span></p>";
            using (var wt = new StreamWriter(context.Response.OutputStream))
                wt.Write(string.Join("", result));
        }

        private static void test2(HttpListenerContext context, string[] path)
        {
            context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
            context.Response.Close();
        }

        private static void test3(HttpListenerContext context, string[] path)
        {
            var sb = new StringBuilder("输入请求:");
            sb.AppendLine(context.Request.Url.LocalPath);
            sb.AppendLine(string.Format("执行命令:{0}", path[0]));
            sb.AppendLine(string.Format("另外有{0}个参数", path.Length - 1 + context.Request.QueryString.Count));
            sb.AppendLine(DateTime.Now.ToString());
            context.Response.ContentType = "text/plain;charset=UTF-8";
            var result = Encoding.UTF8.GetBytes(sb.ToString());
            using (var stream = context.Response.OutputStream)
            {
                stream.Write(result, 0, result.Length);
            }
        }
    }
}



http://localhost:9876/abcd/aa.jsp?p=oooo&d=kslasdfdfs
http://localhost:9876/ef/
http://localhost:9876/12/

#8


HttpListener 

Socket

#9


注意,在win7以上操作系统,服务程序都需要“以管理员身份”启动。开发时,你的vs需要以管理员身份启动。

#10


好像就是那个httplistener

#11


http自服务,其实是相当容易的。一个.net程序设计师,就应该这种开发服务器程序的能力。不论是你的客户端是网页javascript富客户端应用程序,还是什么别的平台的程序,你懒得编写什么tcp程序的时候,编写HttpListener程序也是可以提供服务的。比如说你可以让客户端使用
new WebClient().UploadData(url, datas);
上传数据,然后在你的winfrom程序中通过
context.Request.InputStream
获取到datas数据。而且你也可以看到,技术上并不复杂,缺少的就是实践。

如果你仅仅热衷于把时间都用在跑到网上下载什么框架,你可能耽误宝贵的好几年时间。从现在开始,学会自己编写框架程序吧!

#12



        public bool RequestLoginInput()
        {
            bool retval = true;

            string sServerUrl = @"http://XX.XX.XX.XX/login.jsp";
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(sServerUrl);

            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = 0;
            string ResponseStr;
            req.AllowAutoRedirect = false;
            req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
            req.KeepAlive = true;
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322)";
            req.ContentType = "application/x-www-form-urlencoded";
            try
            {
                using (HttpWebResponse wr = (HttpWebResponse)req.GetResponse())
                {
                    Stream ResStream = wr.GetResponseStream();
                    string tempString = null;
                    int count = 0;
                    byte[] buf = new byte[8192];
                    StringBuilder sb = new StringBuilder();

                    do
                    {
                        // fill the buffer with data
                        count = ResStream.Read(buf, 0, buf.Length);

                        // make sure we read some data
                        if (count != 0)
                        {
                            // translate from bytes to ASCII text
                            tempString = Encoding.UTF8.GetString(buf, 0, count);

                            // continue building the string
                            sb.Append(tempString);
                        }
                    } while (count > 0); // any more data to read?
                    ResponseStr = sb.ToString();
                }

                object[] oPageText = { ResponseStr };
                HTMLDocument document = new HTMLDocumentClass();
                IHTMLDocument2 doc = (IHTMLDocument2)document;
                try
                {
                    string strResponse = ResponseStr;
                    doc.write(oPageText);
                    if (null != document)
                    {
                    }
                }
                catch 
                {
                }

                mshtml.HTMLDocumentClass logindocument = (mshtml.HTMLDocumentClass)document;
                mshtml.HTMLFormElement loginform = (mshtml.HTMLFormElement)logindocument.getElementById("loginform");
                mshtml.HTMLInputElement username = (mshtml.HTMLInputElement)logindocument.getElementById("username");
                mshtml.HTMLInputElement textPassword = (mshtml.HTMLInputElement)logindocument.getElementById("password");
                mshtml.HTMLInputElement rememberpwd = (mshtml.HTMLInputElement)logindocument.getElementById("savepwd");

                mshtml.HTMLInputElement localArea = (mshtml.HTMLInputElement)logindocument.getElementById("localArea");
                mshtml.HTMLInputElement localNeedAuthId = (mshtml.HTMLInputElement)logindocument.getElementById("localNeedAuthId");
                mshtml.HTMLInputElement roamNeedAuthID = (mshtml.HTMLInputElement)logindocument.getElementById("roamNeedAuthID");
                mshtml.HTMLInputElement allowNumber = (mshtml.HTMLInputElement)logindocument.getElementById("allowNumber");
                mshtml.HTMLSelectElement userOpenAddress = (mshtml.HTMLSelectElement)logindocument.getElementById("userOpenAddress");
                mshtml.HTMLInputElement passwordType = (mshtml.HTMLInputElement)logindocument.getElementById("passwordType");

                LocalArea = localArea.value;
                LocalNeedAuthId = localNeedAuthId.value;
                RoamNeedAuthID = roamNeedAuthID.value;
                AllowNumber = allowNumber.value;
                Username = Properties.Settings.Default.username;
                UserOpenAddress = userOpenAddress.value;
                Password = Properties.Settings.Default.password;
                PasswordType = passwordType.value;

            }
            catch
            {
                retval = false;
            }
            finally
            {
            }
            return retval;
        }