幫朋友做一個通過Web簡單傳輸數據的例子,百度了一下抄了段代碼,完成,效果如下:

其中textBox1里面是客戶端需要傳輸過去的數據,textBox2里面是接收到的返回數據。
代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; namespace WebPost { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string postString = "data1=" + textBox1.Text + "&data2=b";//這里即為傳遞的參數,可以用工具抓包分析,也可以自己分析,主要是form里面每一個name都要加進來 byte[] postData = Encoding.UTF8.GetBytes(postString);//編碼,尤其是漢字,事先要看下抓取網頁的編碼方式 string url = "http://localhost/WebTest1/Receive.aspx";//地址 WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必須加的header,如果改為GET方式的話就去掉這句話即可 byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流 string srcString = Encoding.UTF8.GetString(responseData);//解碼 textBox2.Text = srcString; } } }
服務器端 ASP.NET 代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Receive : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Write (Request.Form["data1"]); Response.Write("收到OK!"); Response.End(); } }
WebClient 代碼抄自:http://blog.163.com/len_sa/blog/static/2102540932012782222526/
感謝原作者。
