用C#的HttpListener获取formdata的示例代码
以下是使用C#的HttpListener获取formdata的示例代码:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace HttpListenerExample
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8080/";
HttpListener listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
Console.WriteLine("Listening on " + url);
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
if (request.HttpMethod == "POST")
{
// Check if the request is sending form data
if (request.ContentType.StartsWith("multipart/form-data"))
{
string boundary = request.ContentType.Substring("multipart/form-data; boundary=".Length);
byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
string formFieldName = null;
string formFieldValue = null;
using (Stream bodyStream = request.InputStream)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = bodyStream.Read(buffer, 0, buffer.Length)) > 0)
{
int start = 0;
int end = bytesRead;
// Check if the buffer contains the boundary
for (int i = 0; i < bytesRead; i++)
{
if (buffer[i] == boundaryBytes[0] && bytesRead - i >= boundaryBytes.Length)
{
bool found = true;
for (int j = 1; j < boundaryBytes.Length; j++)
{
if (buffer[i + j] != boundaryBytes[j])
{
found = false;
break;
}
}
if (found)
{
end = i;
break;
}
}
}
// Process the buffer
if (formFieldName == null)
{
// Find the form field name
string bufferStr = Encoding.UTF8.GetString(buffer, start, end - start);
int nameStartIndex = bufferStr.IndexOf("name=\"");
if (nameStartIndex != -1)
{
int nameEndIndex = bufferStr.IndexOf("\"", nameStartIndex + "name=\"".Length);
if (nameEndIndex != -1)
{
formFieldName = bufferStr.Substring(nameStartIndex + "name=\"".Length, nameEndIndex - (nameStartIndex + "name=\"".Length));
}
}
}
else
{
// Find the form field value
string bufferStr = Encoding.UTF8.GetString(buffer, start, end - start);
formFieldValue += bufferStr;
}
// Check if the buffer contains the end boundary
if (end + boundaryBytes.Length < bytesRead && buffer[end + boundaryBytes.Length] == '-')
{
// End of form data
break;
}
}
}
Console.WriteLine("Form field name: " + formFieldName);
Console.WriteLine("Form field value: " + formFieldValue);
// Send response
string responseString = "Form field name: " + formFieldName + "\r\nForm field value: " + formFieldValue;
byte[] responseBytes = Encoding.UTF8.GetBytes(responseString);
response.ContentType = "text/plain";
response.ContentLength64 = responseBytes.Length;
response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
}
}
response.Close();
}
}
}
}
此代码演示了如何使用HttpListener来监听HTTP请求,并从POST请求中获取formdata。此代码支持处理包含多个字段的表单数据,并将每个字段的名称和值输出到控制台。此外,它还发送一个简单的响应,包含从表单数据中提取的字段名称和值。
原文地址: https://www.cveoy.top/t/topic/rlO 著作权归作者所有。请勿转载和采集!