|
Get是用來(lái)從服務(wù)器上獲得數(shù)據(jù),而Post是用來(lái)向服務(wù)器上傳遞數(shù)據(jù). HTTP同步請(qǐng)求 // get請(qǐng)求是查詢字符串直接跟在URL后面 //post是把消息體包含查詢字符串,滿足把大量數(shù)據(jù)傳遞給服務(wù)器![]() //發(fā)送請(qǐng)求,"url"為訪問(wèn)的地址 HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url"); //ContentType為數(shù)據(jù)類型 //get請(qǐng)求ContentType為空,post請(qǐng)求ContentType為application/x-www-form-urlencoded req.ContentType = ""; req.Method = "get"; //請(qǐng)求方法為get和post //content消息體,get請(qǐng)求content為空,post請(qǐng)求為要傳遞的參數(shù),如“AcctID=1 string content = ""; req.ContentLength=content.Length; Stream s;![]() s = req.GetRequestStream();//獲取請(qǐng)求數(shù)據(jù)![]() StreamWriter sw = new StreamWriter(s, System.Text.Encoding.ASCII);![]() sw.Write(content);![]() sw.Close();![]() //得到HTTP請(qǐng)求![]() HttpWebResponse res = (HttpWebResponse)req.GetResponse(); s = res.GetResponseStream();![]() StreamReader sr = new StreamReader(s, System.Text.Encoding.ASCII); System.Text.StringBuilder sb = new System.Text.StringBuilder();![]() char[] data = new char[1024];![]() int nBytes;![]() do { nBytes = sr.Read(data, 0, (int)1024); sb.Append(data); } while (nBytes == 1024);![]() //發(fā)送請(qǐng)求,"url"為訪問(wèn)的地址 HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url"); //ContentType為數(shù)據(jù)類型 //get請(qǐng)求ContentType為空,post請(qǐng)求ContentType為application/x-www-form-urlencoded req.ContentType = ""; req.Method = "get"; //請(qǐng)求方法為get和post //content消息體,get請(qǐng)求content為空,post請(qǐng)求為要傳遞的參數(shù),如“AcctID=1 string content = ""; req.ContentLength=content.Length; Stream s;![]() s = req.GetRequestStream();//獲取請(qǐng)求數(shù)據(jù)![]() StreamWriter sw = new StreamWriter(s, System.Text.Encoding.ASCII);![]() sw.Write(content);![]() sw.Close(); Handler h = new Handler(); AsyncCallback callback = new AsyncCallback(h.Callback); //方法 //將請(qǐng)求對(duì)象作為狀態(tài)對(duì)象傳遞 req.BeginGetResponse(callback, req); public class Handler { public void Callback(IAsyncResult ar) { //將Requeststate對(duì)象強(qiáng)制轉(zhuǎn)化為webRequest對(duì)象 HttpWebRequest req = (HttpWebRequest)ar.AsyncState;![]() //得到與這個(gè)請(qǐng)求相關(guān)的響應(yīng)對(duì)象 HttpWebResponse res = (HttpWebResponse)req.EndGetResponse(ar);![]() //開(kāi)始從響應(yīng)流中讀取數(shù)據(jù) Stream s = res.GetResponseStream();![]() StreamReader sr = new StreamReader(s, System.Text.Encoding.ASCII); System.Text.StringBuilder sb = new System.Text.StringBuilder();![]() char[] data = new char[1024];![]() int nBytes;![]() do { nBytes = sr.Read(data, 0, (int)1024); sb.Append(data); } while (nBytes == 1024);![]() } } |
|
|