发送字符串数据
发送数据
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发送和接受任何类型数据
原文:http://www.cnblogs.com/superfeeling/p/3976043.html