C sends an HttpPost request to invoke the WebService method

  • 2020-05-09 19:08:54
  • OfStack


void UpdateContactSign()
        {
           string ServerPage ="http://localhost/WebService/MyService.asmx";
            try
            {
                //ServerPage += "?op=TangramAction";
                ServerPage += "/MyAction";//MyAction is WebService The methods in 
           string strXml="<a ObjID=\"9\"></a>",;// The first 1 A parameter 
           string strData="ContactSign|990011| My data ";// The first 2 A parameter 
           string res = HttpConnectToServer(ServerPage, strXml, strData);
                //MessageBox.Show(res);
            }
            catch (Exception ex)
            {

            }
        }
        // Send a message to the server 
      public string HttpConnectToServer(string ServerPage,string strXml,string strData)
        {
            string postData = "strXml=" + strXml+"&strData="+strData;
            byte[] dataArray = Encoding.Default.GetBytes(postData);
            // Create a request 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerPage);
            request.Method = "POST";
            request.ContentLength = dataArray.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            // Creating an input stream 
            Stream dataStream = null;
            try
            {
                dataStream = request.GetRequestStream();
            }
            catch (Exception)
            {
                return null;// Connection to server failed 
            }
            // Send the request 
            dataStream.Write(dataArray, 0, dataArray.Length);
            dataStream.Close();
            // Read return message 
            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;// Connection to server failed 
            }
            return res;
        }


Related articles: