C#模仿http 發送post或get要求的簡略實例。本站提示廣大學習愛好者:(C#模仿http 發送post或get要求的簡略實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#模仿http 發送post或get要求的簡略實例正文
private string HttpPost(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); request.CookieContainer = cookie; Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); myStreamWriter.Write(postDataStr); myStreamWriter.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Cookies = cookie.GetCookies(response.ResponseUri); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } public string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
在post的時刻有時也用的到cookie,像登錄163發郵件時刻就須要發送cookie,所以在內部一個cookie屬性隨時保留 CookieContainer cookie = new CookieContainer();
留意:有時刻要求會重定向,但我們就須要從重定向url獲得器械,像QQ登錄勝利後獲得sid,但下面的會主動依據重定向地址跳轉。我們可以用:
request.AllowAutoRedirect = false;設置重定向禁用,你便可以從headers的Location屬性中獲得重定向地址
以上這篇C#模仿http 發送post或get要求的簡略實例就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。