C#做一个Http协议接口
时间: 2023-08-10 09:16:47 浏览: 110
下面是一个简单的C# Http协议接口示例,可以响应GET和POST请求:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
class HttpServer {
public static void Main(string[] args) {
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/"); // 监听的地址和端口号
listener.Start();
Console.WriteLine("Listening...");
while (true) {
// 等待请求
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
Console.WriteLine("{0} {1}", request.HttpMethod, request.Url);
// 处理GET请求
if (request.HttpMethod == "GET") {
string responseString = "Hello World!";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
// 处理POST请求
else if (request.HttpMethod == "POST") {
StreamReader reader = new StreamReader(request.InputStream);
string requestBody = reader.ReadToEnd();
Console.WriteLine("Request Body: {0}", requestBody);
string responseString = "Received Request: " + requestBody;
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
}
}
}
```
在上面的示例中,我们监听了地址和端口号为`http://localhost:8080/`的请求。当接收到GET请求时,返回"Hello World!";当接收到POST请求时,返回收到的请求体。你可以根据实际需求修改响应的内容和处理方法。
阅读全文