private string HttpPost( stringUrl,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 =newStreamWriter(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 =newStreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
stringretString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
returnretString;
}
publicstringHttpGet(stringUrl,stringpostDataStr)
{
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 =newStreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
stringretString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
returnretString;
}
在post的時(shí)候有時(shí)也用的到cookie洞渔,像登錄163發(fā)郵件時(shí)候就需要發(fā)送cookie堡妒,所以在外部一個(gè)cookie屬性隨時(shí)保存 CookieContainer cookie = new CookieContainer();
员凝!注意:有時(shí)候請(qǐng)求會(huì)重定向咆槽,但我們就需要從重定向url獲取東西,像QQ登錄成功后獲取sid瓣履,但上面的會(huì)自動(dòng)根據(jù)重定向地址跳轉(zhuǎn)船响。我們可以用:
request.AllowAutoRedirect = false;設(shè)置重定向禁用,你就可以從headers的Location屬性中獲取重定向地址