http服务(postman调用方法及反参)

#region 监听url

#region 监听url路径请求
static HttpListener httpobj;
private void listeningUrl()
{
//提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
httpobj = new HttpListener();
//定义url及端口号,通常设置为配置文件
httpobj.Prefixes.Add("http://*:9000/");
//启动监听器
httpobj.Start();
//异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
//该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
httpobj.BeginGetContext(Result, null);
//MessageBox.Show("服务端初始化完毕...");
}
#endregion

#region 监听URL方法实现
public void Result(IAsyncResult ar)
{
//当接收到请求后程序流会走到这里

//继续异步监听
httpobj.BeginGetContext(Result, null);
var guid = Guid.NewGuid().ToString();
Console.ForegroundColor = ConsoleColor.White;
//获得context对象
var context = httpobj.EndGetContext(ar);
var request = context.Request;
var response = context.Response;


context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息
context.Response.ContentEncoding = Encoding.UTF8;
string returnObj = null;//定义返回客户端的信息
if (request.HttpMethod == "POST" && request.InputStream != null)
{
Stream stream = request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
string body = reader.ReadToEnd();

string ReturnData = btnSend(body);//调用C#要触发的方法
//处理客户端发送的请求并返回处理信息
returnObj = HandleRequest(ReturnData, response);
// Encode= Base64Encode(returnObj);
}
else
{
returnObj = $"不是post请求或者传过来的数据为空";
}
var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码
try
{
using (var stream = response.OutputStream)
{
//把处理信息返回到客户端
stream.Write(returnByteArr, 0, returnByteArr.Length);
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"网络蹦了:{ex.ToString()}");
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"请求处理完成:{guid},时间:{ DateTime.Now.ToString()}\r\n");
}

private static string HandleRequest(string request, HttpListenerResponse response)
{

StringBuilder jsonPeoples = new StringBuilder();
string error = string.Empty;//错误信息
int code = 0;//成功失败
string message = string.Empty;//成功失败状态
try
{
code = 200;
message = "操作成功";
response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
Console.ForegroundColor = ConsoleColor.Green;
//获取得到数据data可以进行其他操作
}
catch (Exception ex)
{
code = 404;
message = "系统异常,请稍后再试";
response.StatusDescription = "404";
response.StatusCode = 404;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
error = ex.ToString();
return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考
}

jsonPeoples.Append("{");
jsonPeoples.AppendFormat("\"code\":\"{0}\",\"message\":\"{1}\", \"result\":\"{2}\", \"error\":\"{3}\"", code, message, request, error);
jsonPeoples.Append("}");
return jsonPeoples.ToString();
}
#endregion

#endregion

posted @ 2021-11-08 10:19  fulllove  阅读(632)  评论(0)    收藏  举报