C#调用webservice接口的最新方法教程

2019-12-30 18:50:12于丽

那有没有其它方法呢?答案是有的。一种是直接封装信封,使用WebRequest,代码如下:


private void button2_Click(object sender, EventArgs e)
 {
  StringBuilder soap = new StringBuilder();
  soap.Append("<soap:Envelope xmlns:soap="http://www.easck.com/2003/05/soap-envelope" xmlns:zls="www.zlsoft.cn">");
  soap.Append("<soap:Header>");
  soap.Append("<wsse:Security soap:mustUnderstand="true" xmlns:wsse="http://www.easck.com/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://www.easck.com/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">");
  soap.Append("<wsse:UsernameToken wsu:Id="UsernameToken-4">");
  soap.Append("<wsse:Username>hjq</wsse:Username>");//用户名
  soap.Append("<wsse:Password Type="http://www.easck.com/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">123</wsse:Password>");//口令
  soap.Append("<wsse:Nonce EncodingType="http://www.easck.com/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">gC6dDGKjxo0IaRc5KpQU3w==</wsse:Nonce>");
  soap.Append("<wsu:Created>2017-11-01T05:11:22.805Z</wsu:Created>");
  soap.Append("</wsse:UsernameToken>");
  soap.Append("</wsse:Security>");
  soap.Append("</soap:Header>");
  soap.Append("<soap:Body>");
  soap.Append("<zls:getUserInfo>");
  soap.Append("<zls:appsys_id>trwetre</zls:appsys_id>");
  soap.Append("<zls:appsys_token>sdafdsf</zls:appsys_token>");
  soap.Append("<zls:sid>fdsafds</zls:sid>");
  soap.Append("</zls:getUserInfo>");
  soap.Append("</soap:Body>");
  soap.Append("</soap:Envelope>");

  string url = "http://www.easck.com/services/HIPService?wsdl";
  var result = GetSOAPReSource(url, soap.ToString());
 }


  public static string GetSOAPReSource(string url, string datastr)
  {
  try
  {
   //request
   Uri uri = new Uri(url);
   WebRequest webRequest = WebRequest.Create(uri);
  webRequest.ContentType = "application/soap+xml; charset=utf-8";
   webRequest.Method = "POST";
   using (Stream requestStream = webRequest.GetRequestStream())
   {
   byte[] paramBytes = Encoding.UTF8.GetBytes(datastr.ToString());
   requestStream.Write(paramBytes, 0, paramBytes.Length);
   }
   //response
   WebResponse webResponse = webRequest.GetResponse();
   using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
   {
   string result = "";
   return result = myStreamReader.ReadToEnd();
  }
 
  }
  catch (Exception ex)
  {
   throw ex;
  }
 
  }

但是上述方式还是存在问题,如果webservice需要校验header里面的用户名与密码时,虽然信封中封装了用户名和密码,但是一样调用不成功,同样的信封内容,使用SOAP UI却能成功。可见代码调用和SOAP UI调用还是有一定区别的。