asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了webservice的两种调用方式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如下@H_772_1@

service;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.serviceModel;
using System.serviceModel.ChAnnels;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.serialization;

namespace ConsoleApplication1
{
class Program
{
static void Main(String[] args)
{
Hashtable ht = new Hashtable();
ht.Add("customer",new Customer { Id = 1 });
ht.Add("code",1);
var result = WebserviceCaller.QuerySoapWebservice("http://localhost:49644/TestWebService.asmx","HelloWorld",ht);@H_772_1@

        Uri uri = new Uri("http://localhost:49644/TestWebservice.asmx");

        BasichttpSecuritymode securitymode = uri.scheR_993_11845@e.Equals("https",StringComparison.InvariantCultureIgnoreCasE) ? BasichttpSecuritymode.Transport : BasichttpSecuritymode.None;
        BasichttpBinding binding2 = new BasichttpBinding(securitymodE);
        binding2.MaxReceivedmessageSize = int.MaxValue;
        binding2.Name = "TestWebserviceSoap";
        binding2.ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxStringContentLength = int.MaxValue };

        CustomBinding binding = new CustomBinding();
        binding.Name = "TestWebserviceSoap12";
        binding.Elements.Add(new TextmessageEncodingBindingElement()
        {
            messageVersion = messageVersion.Soap12,ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxStringContentLength = int.MaxValue }
        });
        binding.Elements.Add(new httpTransportBindingElement());


        TestWebserviceSoapClient svc = new TestWebserviceSoapClient(binding,new EndpointAddress(uri));
        var str = svc.HelloWorld(new TestWebservice.Customer() { Id = 1 },code: 1);
    }

}

public class Customer
{
    public int id { get; set; }
}

/// <sumMary>
/// 利用Webrequest/WebResponse进行Webservice调用的类
/// </sumMary>
public class WebserviceCaller
{
    #region Tip:使用说明
    //webservices 应该支持Get和Post调用,在web.config应该增加以下代码
    //<webservices>
    // <protocols>
    //  <add name="httpGet"/&gt;
    //  <add name="httpPost"/&gt;
    // </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",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,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,Hashtable Pars)
    {
        if (_xmlNamespaces.ContainsKey(URL))
        {
            return QuerySoapWebservice(URL,MethodName,Pars,_xmlNamespaces[URL].ToString());
        }
        else
        {
            return QuerySoapWebservice(URL,GetNamespace(URL));
        }
    }

    private static XmlDocument QuerySoapWebservice(String URL,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://scheR_993_11845@as.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/XMLscheR_993_11845@a-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLscheR_993_11845@a\" xmlns:soap=\"http://scheR_993_11845@as.xmlsoap.org/soap/envelope/\"&gt;</soap:Envelope>");
        AddDelaration(doc);
        XmlElement soapBody = doc.CreateElement("soap","Body","http://scheR_993_11845@as.xmlsoap.org/soap/envelope/");
        XmlElement soapMethod = doc.CreateElement(MethodName);
        soapMethod.SetAttribute("xmlns",XmlNs);
        foreach (String k in Pars.Keys)
        {
            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"&gt;</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,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("&amp;");
            }
            sb.Append(k + "=" + 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
}

}

@H_772_1@

大佬总结

以上是大佬教程为你收集整理的webservice的两种调用方式全部内容,希望文章能够帮你解决webservice的两种调用方式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: