最近學習Asp.net開發,迷上了Http的傳輸,小試牛刀!
1、Web頁面:
很簡單的一個頁面,功能填入一些資料,儲存到伺服器C盤的一個檔案,:
前台:
View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Nankang.Test.Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>儲存</title></head><body> <form id="form1" runat="server" enableviewstate="False"> <div> <asp:TextBox ID="m_TextBox" runat="server" Height="111px" Width="291px"></asp:TextBox> <br /> <asp:Button ID="m_Button" runat="server" Text="儲存" onclick="m_Button_Click" /> <asp:Label ID="m_Label" runat="server" Text="..."></asp:Label> <br /> </div> </form></body></html>
後台:
View Code
protected void m_Button_Click(object sender, EventArgs e) { StreamWriter sw = null; try { string dir = @"C:\Test\"; if (Directory.Exists(dir) == false) { Directory.CreateDirectory(dir); } string path = dir + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs = new FileStream(path, FileMode.Create); sw = new StreamWriter(fs); sw.WriteLine(this.m_TextBox.Text); this.m_Label.Text += "儲存成功!"; } catch (Exception ex) { this.m_Label.Text = ex.Message; } finally { if (sw != null) { sw.Close(); } } }
2、在WinForm中,用WebClient,調用Post方法,發送資料
頁面:
後台關鍵代碼:
View Code
WebClient webClient = new WebClient(); byte[] responseData = webClient.DownloadData(uriString); string srcString = Encoding.UTF8.GetString(responseData); webClient = new WebClient(); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); //VeiwState string viewStateFlag = "id=\"__VIEWSTATE\" value=\""; int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length; int j = srcString.IndexOf("\"", i); string viewState = srcString.Substring(i, j - i); //EventValidation string eventValidationFlag = "id=\"__EVENTVALIDATION\" value=\""; i = srcString.IndexOf(eventValidationFlag) + eventValidationFlag.Length; j = srcString.IndexOf("\"", i); string eventValidation = srcString.Substring(i, j - i); //擷取頁面的章數 string viewmenuid = "<input name=\"txt_menuid\" type=\"text\" value=\""; i = srcString.IndexOf(viewmenuid) + viewmenuid.Length; j = srcString.IndexOf("\"", i); string txt_menuid = srcString.Substring(i, j - i); //提交按鈕的文本 string submitButton = "儲存"; bookTitle = System.Web.HttpUtility.UrlEncode(bookTitle); viewState = System.Web.HttpUtility.UrlEncode(viewState); eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation); txt_menuid = System.Web.HttpUtility.UrlEncode(txt_menuid); submitButton = System.Web.HttpUtility.UrlEncode(submitButton); string postString = "__VIEWSTATE=" + viewState + "&__EVENTVALIDATION=" + eventValidation + "&m_TextBox=" + bookTitle + "&m_Button=" + submitButton; // 將字串轉換成位元組數組 byte[] postData = Encoding.ASCII.GetBytes(postString); responseData = webClient.UploadData(uriString, "POST", postData); srcString = Encoding.UTF8.GetString(responseData); MessageBox.Show("儲存成功!");
3、Code
源碼下載
僅供參考,謝謝。