代碼如下:
void UpdateContactSign()
{
string ServerPage ="http://localhost/WebService/MyService.asmx";
try
{
//ServerPage += "?op=TangramAction";
ServerPage += "/MyAction";//MyAction是WebService中的方法
string strXml="<a ObjID=\"9\"></a>",;//第一個參數
string strData="ContactSign|990011|我的數據";//第二個參數
string res = HttpConnectToServer(ServerPage, strXml, strData);
//MessageBox.Show(res);
}
catch (Exception ex)
{
}
}
//發送消息到服務器
public string HttpConnectToServer(string ServerPage,string strXml,string strData)
{
string postData = "strXml=" + strXml+"&strData="+strData;
byte[] dataArray = Encoding.Default.GetBytes(postData);
//創建請求
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerPage);
request.Method = "POST";
request.ContentLength = dataArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
//創建輸入流
Stream dataStream = null;
try
{
dataStream = request.GetRequestStream();
}
catch (Exception)
{
return null;//連接服務器失敗
}
//發送請求
dataStream.Write(dataArray, 0, dataArray.Length);
dataStream.Close();
//讀取返回消息
string res = string.Empty;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
res = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex)
{
return null;//連接服務器失敗
}
return res;
}