欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

动态webservice调用接口并读取解析返回结果

程序员文章站 2022-06-09 13:47:19
这里给大家带来的是动态webservice调用接口并读取解析返回结果的具体示例,非常的简单,注释也很详细,小伙伴们可以参考下。 using system; us...

这里给大家带来的是动态webservice调用接口并读取解析返回结果的具体示例,非常的简单,注释也很详细,小伙伴们可以参考下。

using system;
using system.collections;
using system.io;
using system.net;
using system.text;
using system.xml;
using system.xml.serialization;
namespace hishop.plugins
{
  /// <summary>
  /// 利用webrequest/webresponse进行webservice调用的类
  /// </summary>
  public class webservicecaller
  {
    #region tip:使用说明
    //webservices 应该支持get和post调用,在web.config应该增加以下代码
    //<webservices>
    // <protocols>
    //  <add name="httpget"/>
    //  <add name="httppost"/>
    // </protocols>
    //</webservices>
 
    //调用示例:
    //hashtable ht = new hashtable(); //hashtable 为webservice所需要的参数集
    //ht.add("str", "test");
    //ht.add("b", "true");
    //xmldocument xx = websvccaller.querysoapwebservice("http://localhost:81/service.asmx", "helloworld", ht);
    //messagebox.show(xx.outerxml);
    #endregion
 
    /// <summary>
    /// 需要webservice支持post调用
    /// </summary>
    public static xmldocument querypostwebservice(string url, string methodname, hashtable pars)
    {
      httpwebrequest request = (httpwebrequest)httpwebrequest.create(url + "/" + methodname);
      request.method = "post";
      request.contenttype = "application/x-www-form-urlencoded";
      setwebrequest(request);
      byte[] data = encodepars(pars);
      writerequestdata(request, data);
      return readxmlresponse(request.getresponse());
    }
 
    /// <summary>
    /// 需要webservice支持get调用
    /// </summary>
    public static xmldocument querygetwebservice(string url, string methodname, hashtable pars)
    {
      httpwebrequest request = (httpwebrequest)httpwebrequest.create(url + "/" + methodname + "?" + parstostring(pars));
      request.method = "get";
      request.contenttype = "application/x-www-form-urlencoded";
      setwebrequest(request);
      return readxmlresponse(request.getresponse());
    }
 
    /// <summary>
    /// 通用webservice调用(soap),参数pars为string类型的参数名、参数值
    /// </summary>
    public static xmldocument querysoapwebservice(string url, string methodname, hashtable pars)
    {
      if (_xmlnamespaces.containskey(url))
      {
        return querysoapwebservice(url, methodname, pars, _xmlnamespaces[url].tostring());
      }
      else
      {
        return querysoapwebservice(url, methodname, pars, getnamespace(url));
      }
    }
 
    private static xmldocument querysoapwebservice(string url, string methodname, hashtable pars, string xmlns)
    {
      _xmlnamespaces[url] = xmlns;//加入缓存,提高效率
      httpwebrequest request = (httpwebrequest)httpwebrequest.create(url);
      request.method = "post";
      request.contenttype = "text/xml; charset=utf-8";
      request.headers.add("soapaction", "\"" + xmlns + (xmlns.endswith("/") ? "" : "/") + methodname + "\"");
      setwebrequest(request);
      byte[] data = encodeparstosoap(pars, xmlns, methodname);
      writerequestdata(request, data);
      xmldocument doc = new xmldocument(), doc2 = new xmldocument();
      doc = readxmlresponse(request.getresponse());
 
      xmlnamespacemanager mgr = new xmlnamespacemanager(doc.nametable);
      mgr.addnamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
      string retxml = doc.selectsinglenode("//soap:body/*/*", mgr).innerxml;
      doc2.loadxml("<root>" + retxml + "</root>");
      adddelaration(doc2);
      return doc2;
    }
    private static string getnamespace(string url)
    {
      httpwebrequest request = (httpwebrequest)webrequest.create(url + "?wsdl");
      setwebrequest(request);
      webresponse response = request.getresponse();
      streamreader sr = new streamreader(response.getresponsestream(), encoding.utf8);
      xmldocument doc = new xmldocument();
      doc.loadxml(sr.readtoend());
      sr.close();
      return doc.selectsinglenode("//@targetnamespace").value;
    }
 
    private static byte[] encodeparstosoap(hashtable pars, string xmlns, string methodname)
    {
      xmldocument doc = new xmldocument();
      doc.loadxml("<soap:envelope xmlns:xsi=\"http://www.w3.org/2001/xmlschema-instance\" xmlns:xsd=\"http://www.w3.org/2001/xmlschema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"></soap:envelope>");
      adddelaration(doc);
      //xmlelement soapbody = doc.createelement_x_x("soap", "body", "http://schemas.xmlsoap.org/soap/envelope/");
      xmlelement soapbody = doc.createelement("soap", "body", "http://schemas.xmlsoap.org/soap/envelope/");
      //xmlelement soapmethod = doc.createelement_x_x(methodname);
      xmlelement soapmethod = doc.createelement(methodname);
      soapmethod.setattribute("xmlns", xmlns);
      foreach (string k in pars.keys)
      {
        //xmlelement soappar = doc.createelement_x_x(k);
        xmlelement soappar = doc.createelement(k);
        soappar.innerxml = objecttosoapxml(pars[k]);
        soapmethod.appendchild(soappar);
      }
      soapbody.appendchild(soapmethod);
      doc.documentelement.appendchild(soapbody);
      return encoding.utf8.getbytes(doc.outerxml);
    }
    private static string objecttosoapxml(object o)
    {
      xmlserializer myserializer = new xmlserializer(o.gettype());
      memorystream ms = new memorystream();
      myserializer.serialize(ms, o);
      xmldocument doc = new xmldocument();
      doc.loadxml(encoding.utf8.getstring(ms.toarray()));
      if (doc.documentelement != null)
      {
        return doc.documentelement.innerxml;
      }
      else
      {
        return o.tostring();
      }
    }
 
    /// <summary>
    /// 设置凭证与超时时间
    /// </summary>
    /// <param name="request"></param>
    private static void setwebrequest(httpwebrequest request)
    {
      request.credentials = credentialcache.defaultcredentials;
      request.timeout = 10000;
    }
 
    private static void writerequestdata(httpwebrequest request, byte[] data)
    {
      request.contentlength = data.length;
      stream writer = request.getrequeststream();
      writer.write(data, 0, data.length);
      writer.close();
    }
 
    private static byte[] encodepars(hashtable pars)
    {
      return encoding.utf8.getbytes(parstostring(pars));
    }
 
    private static string parstostring(hashtable pars)
    {
      stringbuilder sb = new stringbuilder();
      foreach (string k in pars.keys)
      {
        if (sb.length > 0)
        {
          sb.append("&");
        }
        //sb.append(httputility.urlencode(k) + "=" + httputility.urlencode(pars[k].tostring()));
      }
      return sb.tostring();
    }
 
    private static xmldocument readxmlresponse(webresponse response)
    {
      streamreader sr = new streamreader(response.getresponsestream(), encoding.utf8);
      string retxml = sr.readtoend();
      sr.close();
      xmldocument doc = new xmldocument();
      doc.loadxml(retxml);
      return doc;
    }
 
    private static void adddelaration(xmldocument doc)
    {
      xmldeclaration decl = doc.createxmldeclaration("1.0", "utf-8", null);
      doc.insertbefore(decl, doc.documentelement);
    }
 
    private static hashtable _xmlnamespaces = new hashtable();//缓存xmlnamespace,避免重复调用getnamespace
  }
}

//调用并读取解析返回结果
 
 dataset ds = new dataset(); 
    xmlnode xmlnode1;
    xmldatadocument xd = new xmldatadocument();
    stringbuilder sb; 
    hashtable ht = new hashtable();
    ht.add("xmlin", "<request><memcode>001</memcode></request>");
    xmlnode1 = hishop.plugins.webservicecaller.querysoapwebservice("http://xxx.xxxx.com/service.asmx", "sinpointquery", ht);
    if (xmlnode1 == null)
    {
      return;
    }
    string xmlstr= httputility.htmldecode(xmlnode1.outerxml);
    sb = new stringbuilder(xmlstr);
    if (sb.tostring().equals(""))
    {
      return;
    }
    xd.loadxml(sb.tostring());
    ds.readxml(new xmlnodereader(xd)); 
    //ds可以返回出结果集

以上所述就是本文的全部内容了,希望大家能够喜欢。