Web Service without adding a reference?

前端 未结 6 791
眼角桃花
眼角桃花 2020-12-04 16:16

I have 3 web services added to service references in a class library.(This is a sample project for an API use) I need to move these into my project but i ca

6条回答
  •  一向
    一向 (楼主)
    2020-12-04 16:33

    You can use this class. I didn't remember where i found the basic code, i added some methods and convert to class before.

    public class WebService
    {
        public string Url { get; set; }
        public string MethodName { get; set; }
        public Dictionary Params = new Dictionary();
        public XDocument ResultXML;
        public string ResultString;
    
        public WebService()
        {
    
        }
    
        public WebService(string url, string methodName)
        {
            Url = url;
            MethodName = methodName;
        }
    
        /// 
        /// Invokes service
        /// 
        public void Invoke()
        {
            Invoke(true);
        }
    
        /// 
        /// Invokes service
        /// 
        /// Added parameters will encode? (default: true)
        public void Invoke(bool encode)
        {
            string soapStr =
                @"
                
                  
                    <{0} xmlns=""http://tempuri.org/"">
                      {1}
                    
                  
                ";
    
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);
            req.Headers.Add("SOAPAction", "\"http://tempuri.org/" + MethodName + "\"");
            req.ContentType = "text/xml;charset=\"utf-8\"";
            req.Accept = "text/xml";
            req.Method = "POST";
    
            using (Stream stm = req.GetRequestStream())
            {
                string postValues = "";
                foreach (var param in Params)
                {
                    if (encode)
                        postValues += string.Format("<{0}>{1}", HttpUtility.UrlEncode(param.Key), HttpUtility.UrlEncode(param.Value));
                    else
                        postValues += string.Format("<{0}>{1}", param.Key, param.Value);
                }
    
                soapStr = string.Format(soapStr, MethodName, postValues);
                using (StreamWriter stmw = new StreamWriter(stm))
                {
                    stmw.Write(soapStr);
                }
            }
    
            using (StreamReader responseReader = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                string result = responseReader.ReadToEnd();
                ResultXML = XDocument.Parse(result);
                ResultString = result;
            }
        }
    }
    

    And you can use like this

    WebService ws = new WebService("service_url", "method_name");
    ws.Params.Add("param1", "value_1");
    ws.Params.Add("param2", "value_2");
    ws.Invoke();
    // you can get result ws.ResultXML or ws.ResultString
    

提交回复
热议问题