以下代碼只供參考,大家有興趣可以研究一下。
【1】手機端和服務器端簡單的數據同步
/// <summary>
/// 首先傳參數(strImei,strCode)到服務器然後,下載LocalAllCategory.Xml到手機端-------方法
/// </summary>
/// <param name="URL">服務器URL地址</param>
/// <param name="Filename">存放到本地的路徑</param>
/// <param name="strSortName">類別名稱</param>
/// <param name="strRightMark">權限碼</param>
public static void DownAllCategory(string URL, string Filename, string strImei, string strCode)
{
//向服務器傳參數
string postData = strImei+"&"+strCode;
byte[] bytes = Encoding.UTF7.GetBytes(postData); //注意中文參數需要UTF7編碼方式
HttpWebRequest Myrq = (HttpWebRequest)WebRequest.Create(URL);
Myrq.Method = "POST";
Myrq.ContentLength = bytes.Length;
Myrq.ContentType = "application/x-www-form-urlencoded";
try
{
using (Stream requestStream = Myrq.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
}
//下載文件開始
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
//Prog.Maximum = (int)totalBytes;
Stream st = myrp.GetResponseStream();
Stream so = new FileStream(Filename, FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
Application.DoEvents();
so.Write(by, 0, osize);
//Prog.Value = (int)totalDownloadedByte;
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
//下載文件結束
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk,
MessageBoxDefaultButton.Button1);
}
}
【2】下載文件【Http通信】
/// <summary>
/// 下載方法(帶進度條)
/// </summary>
/// <param name="URL">服務器URL地址</param>
/// <param name="Filename">存放到本地的路徑</param>
/// <param name="Prog">進度條</param>
public string DownCategoryFile(string URL, string Filename, ProgressBar Prog)
{
try
{
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(URL);
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
Prog.Maximum = (int)totalBytes;
Stream st = myrp.GetResponseStream();
Stream so