C#get ,post

來源:互聯網
上載者:User

標籤:cat   ebe   false   讀取   cep   bsp   als   method   using   

(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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.