使用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 + "\r\n"); 85 byte[] EndBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); 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("\r\n")) 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("\r\n", ""); 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