標籤:style blog http color io os 使用 ar strong
發送字串資料
發送資料
string strId = "guest"; string strPassword = "123456"; string postData = "userid=" + strId; postData += ("&password=" + strPassword); byte[] data = Encoding.UTF8.GetBytes(postData); // Prepare web request... HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8058/PostResult.aspx"); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); newStream.Close(); // Get response HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default); string content = reader.ReadToEnd(); Response.Write(content);
接收資料
Stream s = Request.InputStream; StreamReader sr = new StreamReader(s); string ss = sr.ReadToEnd(); Response.Write(ss);
發送任意類型資料
發送資料
//當前頁面地址 string currentUrl = Request.Url.ToString(); string fileName = "複製檔案"; string url = currentUrl.Substring(0, currentUrl.LastIndexOf(‘/‘)) + "/Default2.aspx?id=" + fileName; //發送到的頁面的地址 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); //讀取一個檔案 FileStream fs = new FileStream(Server.MapPath("程式更新說明書.doc"), System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] filecontent = new byte[fs.Length]; fs.Read(filecontent, 0, filecontent.Length); fs.Close(); fs.Dispose(); //將圖片轉換成base64編碼的流 string a = Convert.ToBase64String(filecontent); //讀取base64編碼流,發送 byte[] requestBytes = System.Text.Encoding.Default.GetBytes(a); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = requestBytes.Length; Stream requestStream = req.GetRequestStream(); requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Close(); //接收返回參數,到string backstr HttpWebResponse res = (HttpWebResponse)req.GetResponse(); StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default); string backstr = sr.ReadToEnd(); sr.Close(); res.Close(); //輸出參數 Response.Write(backstr);
接收資料
//接收到的參數 string bb = Request.QueryString["id"]; Encoding myEncoding = Encoding.GetEncoding("utf-8"); //接收傳遞過來的資料流 Stream resStream = Request.InputStream; byte[] filecontent = new byte[resStream.Length]; //將資料流讀入byte數組 resStream.Read(filecontent, 0, filecontent.Length); //數群組轉換為string以便轉換base64使用 string a = myEncoding.GetString(filecontent); //將string讀取base64解密到byte數組 byte[] filecontent2 = Convert.FromBase64String(a); //寫入目錄 File.WriteAllBytes(Server.MapPath(bb + ".doc"), filecontent2); //傳回值 Response.Write("ok"); Response.End();
來源:北京網站建設-恒動時空
Asp.net HttpWebRequest和HttpWebResponse發送和接受任何類型資料