在应用程序中有时需要一个http接口来与第三方通讯。
下面是个简单的代码示例:
1 public async void StartHttpListener(string url) 2 { 3 HttpListener httpListener=new HttpListener(); 4 httpListener.Prefixes.Add(url); 5 httpListener.Start(); 6 while(true) 7 { 8 var requestinfo=await httpListener.GetContextAsync(); 9 if(requestinfo.Request.HttpMethod=="POST") 10 { 11 var requestEntity=await requestinfo.ReadFromJsonAsync<RequestEntityClass>();//json转为对象 12 if(requestEntity!=null) 13 { 14 15 } 16 else 17 { 18 await requestinfo.WriteAsJsonAsync(new ResponseInfo{ code="2",message="error"}); 19 } 20 } 21 request.Response.ContentType = "application/json"; 22 request.Response.ContentEncoding = Encoding.UTF8; 23 request.Response.OutputStream.Flush(); 24 request.Response.OutputStream.Close(); 25 request.Response.OutputStream.Dispose(); 26 } 27 }View Code
标签:OutputStream,http,C#,request,requestinfo,httpListener,手写,Response From: https://www.cnblogs.com/follow-discoverer/p/18031063