使用HttpListener从网页接收数据

本文关键字:数据 网页 HttpListener 使用 | 更新日期: 2023-09-27 17:54:31

我遇到了一个小问题。我目前正在开发一个程序,该程序必须在提交表单时从网页接收数据,

所以我想做的是:当用户按下网页上的提交按钮时,c#程序应该把它捡起来并显示在控制台中。

我怎么能做到这一点,因为我不能再走了?

我发现了很多例子,但似乎没有一个是有效的。这是我举的例子:http://www.codeproject.com/Articles/599978/An-HttpListener-Server-for-Handling-AJAX-POST-Re

我们的代码。

c#代码

    public static void StartListening()
    {        
        HttpListener listener = new HttpListener();
        SetPrefixes(listener);
        if (listener.Prefixes.Count > 0)
        {
            listener.Start();
            Console.WriteLine("HttpClient Started");  
            while(true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request= context.Request;
                HttpListenerResponse response = context.Response;
// this is were i included the SetContent()
                string html = Properties.Resources.index;
                byte[] webPageBuffer = Encoding.UTF8.GetBytes(html);
                response.ContentLength64 = webPageBuffer.Length;
                Stream ouputStream = response.OutputStream;
                ouputStream.Write(webPageBuffer, 0, webPageBuffer.Length);
                ouputStream.Flush();
                Common.Wait(2000);  
                String url = request.RawUrl;
                String[] queryStringArray = url.Split('/');
                String postedtext = GetPostedText(request);

                byte[] buffer = null;
                // Lots of if statements because a switch would not work here.
                if(queryStringArray[0] == "myForm")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved myForm");
                }
                if(queryStringArray[1] == "doSomething")
                {
                    buffer = System.Text.Encoding.UTF8.GetBytes("I recieved doSomething");
                }
                if(buffer != null)
                {
                    response.AddHeader("Cache-Control", "no-cache");
                    response.AddHeader("Acces-Control-Allow-Origin","*");
                    response.ContentLength64 = buffer.Length;
                    Stream secondStream = response.OutputStream;                       
                    secondStream.Write(buffer, 0, buffer.Length);
                    secondStream.Close();
                }
            }
        }
    }
    private static void SetPrefixes(HttpListener listener)
    {
        String[] prefixes = new String[] { "http://localhost:8000/", "http://192.168.33.28:8000/" };
        int i = 0;
        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
            i++;
        }
    }

    private static string GetPostedText(HttpListenerRequest request)
    {
        string recievedText;
        using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
        {
            recievedText= reader.ReadToEnd();
        }
        if (recievedText != "")
        {
            Console.WriteLine("{0} RECIEVED: " + recievedText, DateTime.Now);
        }
        return recievedText;
    }

}

<html>
<head> 
    <title>LocatieScanner</title>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <style>
        body{
    font-size: 12px;
    font-family: Arial;
    }
    legend{
        font-weight: bold;
        font-size: 14px !important;
    }

    fieldset{
        width:200px;
        margin: 0;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-right: -50%;
        transform: translate(-50%, -50%) }
    .wrapper{
        width: 100%;
    }
    </style>

    <script language="javascript">
    //<!-- Create variable timer -->
        var timer;

    //<!-- Create Fucntion CheckOne -->
    /* 
        Wannneer de functie aangroepen word, word eerst de timeout van de variable timer geleegd.
        Daarna word er een timeout ingesteld van 2000 (2sec). Die timeout wordt ingeschakeld nadat het textveld niet meer actief beschouwd word(niet meer gebruikt word, de focus blijft wel op het veld.).
        Na die 2 seconden krijgt de volgende textbox de focus met de zelfde manier maar onder een andere functie.
        Zodra hier ook de 2 seconden om zijn verspringt de focus weer maar nu naar een sumbit (verzenden) knop. Dit is gedaan omdat je dan makkelijk op een OK knop kan drukken op het apparaat.
    */
        function CheckOne() {
             clearTimeout(timer)
             timer = setTimeout(function(){
                 document.getElementById("two").focus();
                 //clearTimeout(timer);
             }, 750)
        }
        function CheckTwo(){
            clearTimeout(timer);
            timer = setTimeout(function(){
                 document.getElementById("sub").focus();
             }, 750)
        }

    </script> 


</head> 
<body> 
<div class="wrapper"> 
    <fieldset> 
        <legend>Locatiescanner</legend><br/> 
        <form id="searchForm" action="http://localhost:8000/myForm/doSomething" >
            Locatienummer: <br />
            <input type="text" id="one" onkeyup="CheckOne()" name="locatienummer"><br />
            Bonnummer: <br />
            <input type="text" id="two" onkeyup="CheckTwo()" name="bonnummer"><br /><br />
            <input id="sub" type="submit" value="Verzenden" />
        </form> 
    </fieldset> 
</div> 
<!-- Include the needed files--> 
    <script>
$("#searchForm").submit(function (event)
{
    // Stop form from submitting normally
    event.preventDefault();
    // Get some values from elements on the page:
    var $form = $(this),
    locatieValue = $form.find("input[name='locatienummer']").val(),
    bonValue = $form.find("input[name='bonnummer']").val(),
    url = $form.attr("action");
    // Send the data using post
    $.post(url, { a: locatieValue, b: bonValue });
});
    </script>
</body> 
</html>

当我收到错误信息时:在一个不存在的网络连接上尝试操作

 private static string GetPostedText(HttpListenerRequest request)
    {
        string recievedText;
        using(StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
        {
       Where i Get the error-->>>     recievedText= reader.ReadToEnd();
        }
        if (recievedText != "")
        {
            Console.WriteLine("{0} RECIEVED: " + recievedText, DateTime.Now);
        }
        return recievedText;
    }

可能的问题

问题可能在这里

                String url = request.RawUrl;
                String[] queryStringArray = url.Split('/');
                String postedtext = GetPostedText(request);

当我通过我的断点,我看到我想在queryStringArray的URL,但由于while循环,它每次重置,所以我不能得到我想要的数据。

并且queryStringArray的长度并不总是相同的。

能帮我一下吗?

使用HttpListener从网页接收数据

试试作为你的html部分:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.post demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="http://localhost:8000/myForm/doSomething" id="searchForm">
    Locatienummer:<input type="text" name="a" placeholder="...">
    <br />
    <br />
    Bonnummer:<input type="text" name="b" placeholder="...">
    <br />
    <br />
    <input type="submit" value="OK">
</form>
  <!-- the result of the search will be rendered inside this div -->
  <div id="result"></div>
    <script type="text/javascript">
        // Attach a submit handler to the form
        $("#searchForm").submit(function (event)
        {
            // Stop form from submitting normally
            event.preventDefault();
            // Get some values from elements on the page:
            var $form = $(this),
            aValue = $form.find("input[name='a']").val(),
            bValue = $form.find("input[name='b']").val(),
            url = $form.attr("action");
            // Send the data using post
            $.post(url, { a: aValue, b: bValue });
        });
    </script>
</body>
</html>

这是HttpListener:

using System;
using System.Net;
using System.Threading;
using System.IO;
namespace MyNameSpace
{
    public class Program
    {    
        static void Main(string[] args)
        {
            Thread thread = new Thread(StartListening);
            thread.Start();
        }
        private static void StartListening()
        {
            HttpListener listener = new HttpListener();
            SetPrefixes(listener);
            if (listener.Prefixes.Count > 0)
            {
                listener.Start();
                while (true)
                {
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    String url = request.RawUrl;
                    String[] queryStringArray = url.Split('/');
                    string postedText = GetPostedText(request);
                    HttpListenerResponse response = context.Response;
                    byte[] buffer = null;
                    if (queryStringArray[1] == "myForm")
                    {
                        buffer = System.Text.Encoding.UTF8.GetBytes("I received myForm");
                    }
                    if (queryStringArray[2] == "doSomething")
                    {
                        buffer = System.Text.Encoding.UTF8.GetBytes("I received doSomething");
                    }
                    if (buffer != null)
                    {
                        response.AddHeader("Cache-Control", "no-cache");
                        response.AddHeader("Access-Control-Allow-Origin", "*");
                        response.ContentLength64 = buffer.Length;
                        Stream outputStream = response.OutputStream;
                        outputStream.Write(buffer, 0, buffer.Length);
                        outputStream.Close();
                    }
                }
            }
        }
        private static void SetPrefixes(HttpListener listener)
        {
            String[] prefixes = new String[] { "http://localhost:8000/" };
            int i = 0;
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
                i++;
            }
        }
        private static string GetPostedText(HttpListenerRequest request)
        {
            string text = "";
            using (StreamReader reader = new StreamReader(request.InputStream, request.ContentEncoding))
            {
                text = reader.ReadToEnd();
            }
            return text;
        }
    }
}

你可以看到你在c#侧的postedText变量框中输入的文本。

我希望这对你有帮助。

编辑:

注释掉下面的行,然后再试一次:

// this is were i included the SetContent()
string html = Properties.Resources.index;
byte[] webPageBuffer = Encoding.UTF8.GetBytes(html);
response.ContentLength64 = webPageBuffer.Length;
Stream ouputStream = response.OutputStream;
ouputStream.Write(webPageBuffer, 0, webPageBuffer.Length);
ouputStream.Flush();
Common.Wait(2000);