.net core使用post请求动态访问WebService接口

时间: 2023-08-15 admin 互联网

.net core使用post请求动态访问WebService接口

.net core使用post请求动态访问WebService接口

.net core使用post请求动态访问WebService接口

        public string CallWebService(string soapText, string webWebServiceUrl)
        {
            using (WebClient webClient = new WebClient())
            {
                try
                {
                    webClient.Proxy = null;
                    byte[] postDatabyte = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(soapText);

                    webClient.Headers.Add("Content-Type", "text/xml");
                    byte[] responseData = webClient.UploadData(webWebServiceUrl, "POST", postDatabyte);
                    //解码 
                    string responsestring = System.Text.Encoding.GetEncoding("UTF-8").GetString(responseData);
                    LogHelper.Warn("webservice请求成功!--" + soapText);
                    return responsestring;
                }
                catch (Exception e)
                {
                    LogHelper.Error("webservice请求错误!", e);
                    return null;
                }
            }

        }

使用方法

webservice地址是不带wsdl的,比如http://localhost:5005/RemoteMonitorService.asmx
请求参数soapText必须是符合Soap请求标准格式比如

<soapenv:Envelope xmlns:soapenv="/" xmlns:tem="/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:RmServiceReceiveHIS>
         <!--参数1-->
         <tem:XmlTypeCode>?</tem:XmlTypeCode>
         <!--参数2-->
         <tem:xmlParams>?</tem:xmlParams>
      </tem:RmServiceReceiveHIS>
   </soapenv:Body>
</soapenv:Envelope>

调用示例

            WebServiceHelper webServiceHelper = new WebServiceHelper();
            var soapText = "<soapenv:Envelope xmlns:soapenv=\"/\" xmlns:tem=\"/\"><soapenv:Header/><soapenv:Body><tem:RmServiceReceiveHIS><!--Optional:--><tem:XmlTypeCode>?</tem:XmlTypeCode><!--Optional:--><tem:xmlParams>?</tem:xmlParams></tem:RmServiceReceiveHIS></soapenv:Body></soapenv:Envelope>";
            var result= webServiceHelper.CallWebService(soapText, "http://localhost:5005/RemoteMonitorService.asmx");
            return "成功";