程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#發送HttpPost請求來調用WebService的方法

C#發送HttpPost請求來調用WebService的方法

編輯:C#基礎知識

代碼如下:

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;
        }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved