1. 程式人生 > >C#get ,post

C#get ,post

char content app html 數據 reat ron ret cep

(1)get

發送url請求

設置請求方式

設置請求內容格式

獲得回應對象,接收流

讀取流

  private string Get(string url)
        {
            string all = string.Empty;
            //發送請求
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "get";//設置方法
            request.ContentType = "
text/html;charset=UTF-8"; //獲得響應 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //讀取流 Stream stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream, Encoding.UTF8); all= sr.ReadToEnd();
//關閉流 stream.Close(); sr.Close(); return all; }

(2)post

發送url請求

設置請求方式

設置請求內容格式

設置請求內容長度(可以不設置)(長度是byte數組的長度,不是string類型的長度)

將post數據添加到請求流中(重中之重GetRequestStream())

接收回應對象,接收流

讀取流

 public static string Post(string postdata, string url)
        {
            HttpWebResponse hw;
            
string result = string.Empty; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/json"; #region 添加Post 參數 byte[] data = Encoding.UTF8.GetBytes(postdata); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length);//將post對象放入請求流中 reqStream.Close(); } #endregion try { HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //獲取響應內容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } catch (WebException w) { hw = (HttpWebResponse)w.Response; StreamReader sr = new StreamReader(hw.GetResponseStream(), Encoding.UTF8, false); result = sr.ReadToEnd(); } return result; }

C#get ,post