我遇到了一个小问题。我目前正致力于在提交表单时必须从网页接收数据的程序,
所以我想要做的是:当用户按下网页上的提交按钮时,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代码
<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
也不总是相同的长度。
我能获得一些帮助吗?
答案 0 :(得分:0)
尝试将其作为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#侧看到您在uploadText变量内的框中输入的文字。
我希望这会对你有所帮助。
编辑:
注释掉以下几行并再试一次:
// 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);