使用httplistener监听来自客户端的http请求,对于Get请求的数据可以通过Request.QueryString["参数"]获取
而对于来自客户端的Post请求则不能使用Request[""]获取,需要将获取分析请求流中的数据拿到参数
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Net; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace HttpListenerPost 10 { 11 /// <summary> 12 /// HttpListenner监听Post请求参数值实体 13 /// </summary> 14 public class HttpListenerPostValue 15 { 16 /// <summary> 17 /// 0=> 参数 18 /// 1=> 文件 19 /// </summary> 20 public int type = 0; 21 public string name; 22 public byte[] datas; 23 } 24 25 /// <summary> 26 /// 获取Post请求中的参数和值帮助类 27 /// </summary> 28 public class HttpListenerPostParaHelper 29 { 30 private HttpListenerContext request; 31 32 public HttpListenerPostParaHelper(HttpListenerContext request) 33 { 34 this.request = request; 35 } 36 37 private bool CompareBytes(byte[] source, byte[] comparison) 38 { 39 try 40 { 41 int count = source.Length; 42 if (source.Length != comparison.Length) 43 return false; 44 for (int i = 0; i < count; i++) 45 if (source[i] != comparison[i]) 46 return false; 47 return true; 48 } 49 catch 50 { 51 return false; 52 } 53 } 54 55 private byte[] ReadLineAsBytes(Stream SourceStream) 56 { 57 var resultStream = new MemoryStream(); 58 while (true) 59 { 60 int data = SourceStream.ReadByte(); 61 resultStream.WriteByte((byte)data); 62 if (data == 10) 63 break; 64 } 65 resultStream.Position = 0; 66 byte[] dataBytes = new byte[resultStream.Length]; 67 resultStream.Read(dataBytes, 0, dataBytes.Length); 68 return dataBytes; 69 } 70 71 /// <summary> 72 /// 获取Post过来的参数和数据 73 /// </summary> 74 /// <returns></returns> 75 public List<HttpListenerPostValue> GetHttpListenerPostValue() 76 { 77 try 78 { 79 List<HttpListenerPostValue> HttpListenerPostValueList = new List<HttpListenerPostValue>(); 80 if (request.Request.ContentType.Length > 20 && string.Compare(request.Request.ContentType.Substring(0, 20), "multipart/form-data;", true) == 0) 81 { 82 string[] HttpListenerPostValue = request.Request.ContentType.Split(';').Skip(1).ToArray(); 83 string boundary = string.Join(";", HttpListenerPostValue).Replace("boundary=", "").Trim(); 84 byte[] ChunkBoundary = Encoding.UTF8.GetBytes("--" + boundary + " "); 85 byte[] EndBoundary = Encoding.UTF8.GetBytes("--" + boundary + "-- "); 86 Stream SourceStream = request.Request.InputStream; 87 var resultStream = new MemoryStream(); 88 bool CanMoveNext = true; 89 HttpListenerPostValue data = null; 90 while (CanMoveNext) 91 { 92 byte[] currentChunk = ReadLineAsBytes(SourceStream); 93 if (!Encoding.UTF8.GetString(currentChunk).Equals(" ")) 94 resultStream.Write(currentChunk, 0, currentChunk.Length); 95 if (CompareBytes(ChunkBoundary, currentChunk)) 96 { 97 byte[] result = new byte[resultStream.Length - ChunkBoundary.Length]; 98 resultStream.Position = 0; 99 resultStream.Read(result, 0, result.Length); 100 CanMoveNext = true; 101 if (result.Length > 0) 102 data.datas = result; 103 data = new HttpListenerPostValue(); 104 HttpListenerPostValueList.Add(data); 105 resultStream.Dispose(); 106 resultStream = new MemoryStream(); 107 108 } 109 else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Disposition")) 110 { 111 byte[] result = new byte[resultStream.Length - 2]; 112 resultStream.Position = 0; 113 resultStream.Read(result, 0, result.Length); 114 CanMoveNext = true; 115 data.name = Encoding.UTF8.GetString(result).Replace("Content-Disposition: form-data; name="", "").Replace(""", "").Split(';')[0]; 116 resultStream.Dispose(); 117 resultStream = new MemoryStream(); 118 } 119 else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Type")) 120 { 121 CanMoveNext = true; 122 data.type = 1; 123 resultStream.Dispose(); 124 resultStream = new MemoryStream(); 125 } 126 else if (CompareBytes(EndBoundary, currentChunk)) 127 { 128 byte[] result = new byte[resultStream.Length - EndBoundary.Length - 2]; 129 resultStream.Position = 0; 130 resultStream.Read(result, 0, result.Length); 131 data.datas = result; 132 resultStream.Dispose(); 133 CanMoveNext = false; 134 } 135 } 136 } 137 return HttpListenerPostValueList; 138 } 139 catch (Exception ex) 140 { 141 return null; 142 } 143 } 144 } 145 }
开启监听,获取Post请求的参数
1 class Program 2 { 3 private static HttpListener httpPostRequest = new HttpListener(); 4 5 static void Main(string[] args) 6 { 7 httpPostRequest.Prefixes.Add("http://10.0.0.217:30000/posttype/"); 8 httpPostRequest.Start(); 9 10 Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle)); 11 ThrednHttpPostRequest.Start(); 12 } 13 14 private static void httpPostRequestHandle() 15 { 16 while (true) 17 { 18 HttpListenerContext requestContext = httpPostRequest.GetContext(); 19 Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) => 20 { 21 HttpListenerContext request = (HttpListenerContext)requestcontext; 22 23 //获取Post请求中的参数和值帮助类 24 HttpListenerPostParaHelper httppost=new HttpListenerPostParaHelper (request); 25 //获取Post过来的参数和数据 26 List<HttpListenerPostValue> lst=httppost.GetHttpListenerPostValue(); 27 28 string userName = ""; 29 string password = ""; 30 string suffix = ""; 31 string adType = ""; 32 33 //使用方法 34 foreach (var key in lst) 35 { 36 if (key.type == 0) 37 { 38 string value = Encoding.UTF8.GetString(key.datas).Replace(" ", ""); 39 if (key.name == "username") 40 { 41 userName = value; 42 Console.WriteLine(value); 43 } 44 if (key.name == "password") 45 { 46 password = value; 47 Console.WriteLine(value); 48 } 49 if (key.name == "suffix") 50 { 51 suffix = value; 52 Console.WriteLine(value); 53 } 54 if (key.name == "adtype") 55 { 56 adType = value; 57 Console.WriteLine(value); 58 } 59 } 60 if (key.type == 1) 61 { 62 string fileName = request.Request.QueryString["FileName"]; 63 if (!string.IsNullOrEmpty(fileName)) 64 { 65 string filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyMMdd_HHmmss_ffff") + Path.GetExtension(fileName).ToLower(); 66 if (key.name == "File") 67 { 68 FileStream fs = new FileStream(filePath, FileMode.Create); 69 fs.Write(key.datas, 0, key.datas.Length); 70 fs.Close(); 71 fs.Dispose(); 72 } 73 } 74 } 75 } 76 77 //Response 78 request.Response.StatusCode = 200; 79 request.Response.Headers.Add("Access-Control-Allow-Origin", "*"); 80 request.Response.ContentType = "application/json"; 81 requestContext.Response.ContentEncoding = Encoding.UTF8; 82 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new {success="true",msg="提交成功" })); 83 request.Response.ContentLength64 = buffer.Length; 84 var output = request.Response.OutputStream; 85 output.Write(buffer, 0, buffer.Length); 86 output.Close(); 87 })); 88 threadsub.Start(requestContext); 89 } 90 }
HttpListener 类一定要在程序结束时手动结束掉(有时调试时,明明程序已经停止,但是监听事件却在后台默默运行),建议把监听事件写在一个线程中,这样的话假如线程停掉,里面的监听事件也就停掉了。
特别注意,因为是新手,我就自以为需要把IIS网站开启才能监听,但是在调试的时候却一直报”占用”错误,后来才慢慢试明白!
另外,因为这次是做微信域名的验证,在微信请求时给微信相应的回复,刚开始就返回一个 true 可是微信说不行,后来整明白啦,原来需要回复的是微信绑定域名时的TXT文档中内容!
这个大坑用了两天终于过去了
使用谷歌请求插件进行post请求 PostMan
转自:http://blog.csdn.net/heyangyi_19940703/article/details/51743167