標籤:
一、向post請求中寫入資料,最終儲存在了HttpWebRequest.Params中:
1)如果存入的是IDictionary類型的字串變數,如:“username=administrator”,則key=value;
2)如果寫入的是string類型的變數,如"username",則key=null,value=username;
protected void btnLogin_Click(object sender, EventArgs e) { string Url = "http://localhost:18472/DataRequest.aspx"; string contentType = "application/x-www-form-urlencoded"; string username = "administrator"; string password = "admin"; IDictionary<string,string> param=new Dictionary<string,string>(); param.Add("username",username); param.Add("password",password); int i = 0; StringBuilder sb=new StringBuilder(); foreach (var key in param.Keys) { if (i>0) { sb.AppendFormat("&{0}={1}", key, param[key]); } else { sb.AppendFormat("{0}={1}", key, param[key]); } i++; } //string content = SendPost(sb.ToString(),Url,contentType); string content = SendPost(username,Url,contentType); } /// <summary> /// /// </summary> /// <param name="data">寫入流中的資料,最後將儲存在request.params中,是Idictionary類型的變數;如果是沒有等號的string類型,key=null,value=string</param> /// <param name="url">請求的url</param> /// <param name="contentType">請求的內容類型</param> /// <returns></returns> public static string SendPost(string data, string url, string contentType) { string content = string.Empty; HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest; httpWebRequest.AllowAutoRedirect = true; httpWebRequest.Method = "POST"; httpWebRequest.ContentType = contentType; using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream())) { sw.Write(data); } HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(), System.Text.Encoding.Default)) { content = sr.ReadToEnd(); } //httpWebRequest.EndGetResponse; return content; }
二、從request中取出寫入的data資料(比如:xml等)的另一種方法:從流中擷取(僅一次)
string content=""; using (Stream stream = HttpContext.Current.Request.InputStream) { using (StreamReader sr = new StreamReader(stream, Encoding.UTF8)) { content=sr.ReadToEnd(); } }
三、實現資料在IHttpModule和IHttpHandler之間(process項目和web項目之間)資料的組織和共用的鍵/值集合,儲存在context.Items中
string XML=content;
HttpContext context=HttpContext.Current;
context.Items.Add("XML", XML);
四、從Items集合中取出資料
string XML=context.Items["XML"].ToString();
向post請求中寫入資料,最終儲存在了HttpWebRequest.Params中