C#利用HttpWebRequest,Stream,HttpWebResponse,StreamReader獲取post返回的數據


轉自 https://blog.csdn.net/canonzki/article/details/52047744 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; namespace TestCon { static class InfoGeter { //靜態方法傳遞兩個參數,Post_String是單純的鏈接,Post_Data是post的參數用以請求 public static string Info_Geter_Post_Get(string Post_String,string Post_Data) { try { string s_Connection_String = Post_String; //實例化一個HttpWebrequst對象 HttpWebRequest Info_Request = (HttpWebRequest)WebRequest.Create(s_Connection_String); //設置Requst的模式 Info_Request.Method = "POST"; //設置Content-Type Http標頭的值,該值為默認值 Info_Request.ContentType = "application/x-www-form-urlencoded"; //預設響應等待時間 Info_Request.Timeout = 20000; //建立一個Stream對象來寫入Requst請求的參數流內涵url和key值等 Stream Info_Stream = Info_Request.GetRequestStream(); //調用Write方法第一個參數是獲取傳遞參數的值得類型,第二個是流起始位置,第三個參數指流的長度 Info_Stream.Write(Encoding.UTF8.GetBytes(Post_Data), 0, Encoding.UTF8.GetBytes(Post_Data).Length); //實例化一個HttpWebResponse用GetResponse方法用以獲取服務器返回的響應 HttpWebResponse Info_Response = (HttpWebResponse)Info_Request.GetResponse(); //實例化一個StreamReader對象來獲取Response的GetResponseStream返回的響應的體 StreamReader Info_Reader = new StreamReader(Info_Response.GetResponseStream(), Encoding.UTF8); return Info_Reader.ReadToEnd()+""; } catch (System.Exception ex) { Console.WriteLine(ex); Console.ReadLine(); return ""; } } } }


免責聲明!

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



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