一個簡單的Httpserver以及獲取post提交的參數


以下代碼是我從網上找來的,但是一直獲取不到post提交的參數,最后經過我的修改,終於可以得到post提交的數據。因為本人在網上找了很久都沒有找到相關的資料,特意發出來希望能幫到大家,有什么不足的地方還請大神們指正,小弟不勝感激。

Httpserver代碼

 1         public void StartListen()
 2         {
 3             using (HttpListener listerner = new HttpListener())
 4             {
 5                 listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份驗證 Anonymous匿名訪問
 6                 listerner.Prefixes.Add("http://localhost:8080/web/");
 7 
 8                 // listerner.Prefixes.Add("http://localhost/web/");
 9                 listerner.Start();
10                 Console.WriteLine("WebServer Start Successed.......");
11                 while (true)
12                 {
13                     //等待請求連接
14                     //沒有請求則GetContext處於阻塞狀態
15                     HttpListenerContext ctx = listerner.GetContext();
16                     ctx.Response.StatusCode = 200;//設置返回給客服端http狀態代碼
17                     //RequestType=1&Longitude=0.0&Latitude=0.0&RequestSource=xx
18                     string RequestType = "";
19                     string Longitude = "";
20                     string Latitude = "";
21                     string RequestSource = "";
22                     //獲取客戶端寫入的信息
23                     string strRequest = ShowRequestData(ctx.Request);
24                     if (!string.IsNullOrEmpty(strRequest))
25                     {
26                         string[] strR = strRequest.Split('&');
27                         string[] strP = new string[strR.Length];
28                         for (int i = 0; i < strR.Length; i++)
29                         {
30                             strP[i] = strR[i].Split('=')[1];
31                         }
32                         RequestType = strP[0];
33                         Longitude = strP[1];
34                         Latitude = strP[2];
35                         RequestSource = strP[3];
36                     }
37                     string strSend = "";
38 
39                     if (!string.IsNullOrEmpty(RequestType))
40                     {
41                         if (RequestType == "1" && !string.IsNullOrEmpty(Longitude) && !string.IsNullOrEmpty(Latitude))
42                         {
43                             strSend = GetPointWeather(Longitude, Latitude, RequestSource);
44                         }
45                         if (RequestType == "2")
46                         { 
47                             
48                         }
49                     }
50 
51                     //使用Writer輸出http響應代碼
52                     using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.GetEncoding("gb2312")))
53                     {
54                         writer.WriteLine(strSend);
55                         writer.Close();
56                         ctx.Response.Close();
57                     }
58 
59                 }
60                 //listerner.Stop();
61             }
62         }

GetPointWeather函數是我自己定義的,主要是得到返回給客戶端的信息。

獲取客戶端的輸入流

 1         public string ShowRequestData(HttpListenerRequest request)
 2         {
 3             if (!request.HasEntityBody)
 4             {
 5                 Console.WriteLine("No client data was sent with the request.");
 6                 return "";
 7             }
 8             System.IO.Stream body = request.InputStream;
 9             System.Text.Encoding encoding = request.ContentEncoding;
10             System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
11             if (request.ContentType != null)
12             {
13                 Console.WriteLine("Client data content type {0}", request.ContentType);
14             }
15             Console.WriteLine("Client data content length {0}", request.ContentLength64);
16 
17             Console.WriteLine("Start of client data:");
18             // Convert the data to a string and display it on the console.
19             string s = reader.ReadToEnd();
20             Console.WriteLine(s);
21             Console.WriteLine("End of client data:");
22             body.Close();
23             reader.Close();
24             // If you are finished with the request, it should be closed also.
25             return s;
26         }

 

post請求代碼:

 1         /// <summary>
 2         /// 使用Http請求天氣信息
 3         /// </summary>
 4         /// <param name="RequestType">請求類別(1:點預報 2:鎮預報)</param>
 5         /// <param name="Longitude">經度(如果是鎮預報請求 值為空)</param>
 6         /// <param name="Latitude">緯度(如果是鎮預報請求 值為空)</param>
 7         /// <param name="RequestSource">請求來源</param>
 8         public void GetWeatherByHttp(string RequestType, string Longitude, string Latitude, string RequestSource)
 9         {
10             string strURL = "http://localhost:8080/web/";
11             System.Net.HttpWebRequest request;
12             request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
13             //Post請求方式  
14             request.Method = "POST";
15             //內容類型  
16             request.ContentType = "application/x-www-form-urlencoded";
17             //參數經過URL編碼  
18             Encoding myEncoding = Encoding.GetEncoding("gb2312");//GetEncoding("gb2312")
19             string paraUrlCoded = HttpUtility.UrlEncode("RequestType", myEncoding);
20             paraUrlCoded += "=" + HttpUtility.UrlEncode(RequestType, myEncoding);
21             paraUrlCoded += "&" + HttpUtility.UrlEncode("Longitude", myEncoding);
22             paraUrlCoded += "=" + HttpUtility.UrlEncode(Longitude, myEncoding);
23             paraUrlCoded += "&" + HttpUtility.UrlEncode("Latitude", myEncoding);
24             paraUrlCoded += "=" + HttpUtility.UrlEncode(Latitude, myEncoding);
25             paraUrlCoded += "&" + HttpUtility.UrlEncode("RequestSource", myEncoding);
26             paraUrlCoded += "=" + HttpUtility.UrlEncode(RequestSource, myEncoding);
27             byte[] payload;
28             //將URL編碼后的字符串轉化為字節  
29             payload = System.Text.Encoding.ASCII.GetBytes(paraUrlCoded);
30             //設置請求的ContentLength   
31             request.ContentLength = payload.Length;
32             //獲得請求流  
33             Stream writer = request.GetRequestStream();
34             //將請求參數寫入流  
35             writer.Write(payload, 0, payload.Length);
36             //關閉請求流  
37             writer.Close();
38             System.Net.HttpWebResponse response;
39             //獲得響應流  
40             response = (System.Net.HttpWebResponse)request.GetResponse();
41             System.IO.Stream s;
42             s = response.GetResponseStream();
43             string StrDate = "";
44             string strValue = "";
45             StreamReader Reader = new StreamReader(s, Encoding.Default);
46             while ((StrDate = Reader.ReadLine()) != null)
47             {
48                 strValue += StrDate + "\r\n";
49             }
50             // txtInfo.Text = strValue;  
51             Reader.Close();
52         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM