C# 通过Get、Post、Soap调用WebService的章程

贯彻代码来源于互联网,我只是作了一部分修改!

读取或生成EXCEL数据的法子有无数,一般常见的有:

using System;
using System.Web;
using System.Xml;
using System.Collections;
using System.Net;
using System.Text;
using System.IO;
using System.Xml.Serialization;


/// <summary>
///  利用WebRequest/WebResponse进行WebService调用的类
/// </summary>
public class WebServiceHelper
{
    //<webServices>
    //  <protocols>
    //    <add name="HttpGet"/>
    //    <add name="HttpPost"/>
    //  </protocols>
    //</webServices>
    private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace

    /// <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));
        }
    }

    /// <summary>
    /// 通用WebService调用(Soap)
    /// </summary>
    /// <param name="URL"></param>
    /// <param name="MethodName"></param>
    /// <param name="Pars"></param>
    /// <param name="XmlNs"></param>
    /// <returns></returns>
    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;
    }

    /// <summary>
    /// 通过WebService的WSDL获取XML名称空间
    /// </summary>
    /// <param name="URL"></param>
    /// <returns></returns>
    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;
    }

    /// <summary>
    /// 动态生成SOP请求报文内容
    /// </summary>
    /// <param name="Pars"></param>
    /// <param name="XmlNs"></param>
    /// <param name="MethodName"></param>
    /// <returns></returns>
    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("soap", "Body", "http://schemas.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);
    }

    /// <summary>
    /// 将对象转换成XML节点格式
    /// </summary>
    /// <param name="o"></param>
    /// <returns></returns>
    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>
    /// 设置WEB请求
    /// </summary>
    /// <param name="request"></param>
    private static void SetWebRequest(HttpWebRequest request)
    {
        request.Credentials = CredentialCache.DefaultCredentials;
        request.Timeout = 10000;
    }

    /// <summary>
    /// 设置请求数据
    /// </summary>
    /// <param name="request"></param>
    /// <param name="data"></param>
    private static void WriteRequestData(HttpWebRequest request, byte[] data)
    {
        request.ContentLength = data.Length;
        Stream writer = request.GetRequestStream();
        writer.Write(data, 0, data.Length);
        writer.Close();
    }

    /// <summary>
    /// 获取字符串的UTF8码字符串
    /// </summary>
    /// <param name="Pars"></param>
    /// <returns></returns>
    private static byte[] EncodePars(Hashtable Pars)
    {
        return Encoding.UTF8.GetBytes(ParsToString(Pars));
    }

    /// <summary>
    /// 将Hashtable转换成WEB请求键值对字符串
    /// </summary>
    /// <param name="Pars"></param>
    /// <returns></returns>
    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();
    }

    /// <summary>
    /// 获取Webservice响应报文XML
    /// </summary>
    /// <param name="response"></param>
    /// <returns></returns>
    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;
    }

    /// <summary>
    /// 设置XML文档版本声明
    /// </summary>
    /// <param name="doc"></param>
    private static void AddDelaration(XmlDocument doc)
    {
        XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        doc.InsertBefore(decl, doc.DocumentElement);
    }
}

1.通过OFFICE
EXCEL组件,优点:读取与生成EXCEL文件方便,缺点:服务器上必须安装OFFICE软件,且经过不可以即时放出

如上是在不引用WEB服务的基准下动态调用WEB服务方法,即使该服务地点不确定或后期有只怕会变动,则使用上述那一个方法会相比好,当然假使服务地方不会冒出改变的情事下,可以在VS中一向引用WEB服务,然后就可调用自动生成的SOAPClient类来调用相应的WEB服务形式,那样就概括很多,如下:

2.通过第三方组件(比如:NPOI),优点:无需安装OFFICE软件,缺点:需求引入第三方组件,当然这几个照旧相比较强的

avar client = new SmsService.wmgwSoapClient(); //wmgwSoapClient就是引用WEB服务后自动生成的类
                string result = client.MongateSendSubmit(tuserId.Text, tpassword.Text, tpszMobis.Text, tpszMsg.Text, int.Parse(tiMobiCount.Text),
                                tpszSubPort.Text, tMsgId.Text);

3.由此把EXCEL当成数据库,连接后使用SQL语句读取,写入的话就机关拼接成HTML表格,优点:无需此外的组件,缺点:须求会SQL及拼接HTML表格较劳累;

越来越多IT相关技术小说与情报,欢迎光临我的村办网站:http://www.zuowenjun.cn

三种艺术本身都有用过,若支付BS网站程序,提出接纳第两种、第二种方法,若支付CS结构,指出使用第一种或第二种;

以下是自家本着BS端写的一个ExcelHelper通用类,可用来读取或变更数据,比较便利,技术原理是上述的第二种格局,代码如下,大概存在缺点,高手见谅:

namespace ASOTS.Models
{
    public abstract class ExcelHelper
    {
        /// <summary>
        /// 获取EXCEL中指定sheet内容
        /// </summary>
        /// <returns></returns>
        public static DataTable GetTableFromExcel(string filePath, string fileExt, string tableName, int colsCount)
        {
            string connstr = null;
            if (fileExt == ".xls")
            {
                connstr = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
            }
            else
            {
                connstr = "Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source =" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
            }

            using (OleDbConnection excelConn = new OleDbConnection(connstr))
            {
                excelConn.Open();

                //获取EXCEL架构信息
                DataTable schemaTable = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });

                //判断指定sheet名是否存在
                DataView schemaView = new DataView(schemaTable);
                schemaView.RowFilter = "TABLE_NAME='" + tableName + "$'";
                schemaTable = schemaView.ToTable();

                if (schemaTable != null && schemaTable.Rows.Count > 0)
                {
                    DataTable schemaTable_Cols = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName + "$", null });
                    schemaView = new DataView(schemaTable_Cols);
                    schemaView.RowFilter = "ORDINAL_POSITION<=" + colsCount.ToString();
                    schemaView.Sort = "ORDINAL_POSITION asc";
                    schemaTable_Cols = schemaView.ToTable();
                    string selectCols = "";
                    for (int i = 0; i < schemaTable_Cols.Rows.Count; i++)
                    {
                        selectCols += "," + schemaTable_Cols.Rows[i]["COLUMN_NAME"].ToString();
                    }

                    selectCols = selectCols.Substring(1);

                    //查询sheet中的数据
                    string strSql = "select " + selectCols + " from [" + tableName + "$]";
                    OleDbDataAdapter da = new OleDbDataAdapter(strSql, excelConn);
                    DataSet ds = new DataSet();
                    da.Fill(ds, tableName);
                    excelConn.Close();
                    return ds.Tables[tableName];
                }
                else
                {
                    excelConn.Close();
                    return null;
                }
            }

        }

        /// <summary>
        /// 将数据模型集合对象生成HTML表格字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="tableAttributes"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static string SetDataToHtmlTable(IEnumerable data, string tableAttributes, params KeyValuePair<string, string>[] headers)
        {
            StringBuilder htmlTableBuilder = new StringBuilder();
            htmlTableBuilder.AppendFormat("<table {0}>", tableAttributes);

            if (data.GetEnumerator().Current == null)
            {
                throw new Exception("没有获取到任何数据!");
            }

            Type t = data.GetEnumerator().Current.GetType();

            string[] cellIndexs = new string[headers.Count()];

            htmlTableBuilder.Append("<tr>");
            for (int i = 0; i < headers.Count(); i++)
            {
                cellIndexs[i] = headers[i].Key;
                htmlTableBuilder.AppendFormat("<th>{0}</th>", headers[i].Value);
            }
            htmlTableBuilder.Append("</tr>");

            foreach (var item in data)
            {
                htmlTableBuilder.Append("<tr>");
                for (int i = 0; i < cellIndexs.Length; i++)
                {
                    object pValue = t.GetProperty(cellIndexs[i]).GetValue(item, null);
                    htmlTableBuilder.AppendFormat("<td>{0}</td>", pValue);
                }
                htmlTableBuilder.Append("</tr>");
            }

            htmlTableBuilder.Append("</table>");

            return htmlTableBuilder.ToString();
        }



        /// <summary>
        /// 将DataTable对象生成HTML表格字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="tableAttributes"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static string SetDataToHtmlTable(DataTable dataTable, string tableAttributes, params KeyValuePair<string, string>[] headers)
        {
            StringBuilder htmlTableBuilder = new StringBuilder();
            htmlTableBuilder.AppendFormat("<table {0}>", tableAttributes);

            htmlTableBuilder.Append("<tr>");
            for (int i = 0; i < headers.Count(); i++)
            {
                htmlTableBuilder.AppendFormat("<th>{0}</th>", headers[i].Value);
            }
            htmlTableBuilder.Append("</tr>");

            foreach (DataRow row in dataTable.Rows)
            {
                htmlTableBuilder.Append("<tr>");
                for (int i = 0; i < headers.Count(); i++)
                {
                    htmlTableBuilder.AppendFormat("<td>{0}</td>", row[headers[i].Key]);
                }
                htmlTableBuilder.Append("</tr>");
            }

            htmlTableBuilder.Append("</table>");

            return htmlTableBuilder.ToString();
        }

    }

    public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
    {
        public void Add(TKey key, TValue value)
        {
            base.Add(new KeyValuePair<TKey, TValue>(key, value));
        }
    }
}

调用方法如下:

//读数据
DataTable resultTable = ExcelHelper.GetTableFromExcel(saveFilePath, fileExt, "data", 10);

//生成表格(以下是MVC调用,WEBFORM同理)
KeyValueList<string, string> headers = new KeyValueList<string, string>() { 
                        {"year","年 份"},
                        {"month","月 份"},
                        {"stage1count","一 阶"},
                        {"stage2count","二 阶"},
                        {"stage3count","三 阶"},
                        {"stage4count","四 阶"},
                        {"yearincount","一年内进厂"},
                        {"stagetotalcount","基盘客户总数"},
                        {"stage1rate","一阶占比"},
                        {"stage2rate","二阶占比"},
                        {"stage3rate","三阶占比"},
                        {"stage4rate","四阶占比"}
                };

                string tableAttributes = "border='1' cellspacing='3' cellpadding='3'";

                string htmlTable=ExcelHelper.SetDataToHtmlTable(model, tableAttributes, headers.ToArray());
                byte[] b = System.Text.Encoding.UTF8.GetBytes(htmlTable);

                return File(b, "application/vnd.ms-excel", string.Format("StageSummary_{0}_{1}_{2}.xls",orgcode,startym,endym));

内部:KeyValueList是自我创设的一个集合类,首要用来转移表头,以及表头与数据列对应,之所以写成类,是因为若直接使用:List<KeyValuePair<TKey,
电视alue>>,则无从直接利用集合早先化器,就必需得一个一个的丰裕对象,有些麻烦,增添了ADD方法后,就可以直接用:new
KeyValueList<string, string>()
{{“”,””},…}很有利,有人恐怕说为何不用SortedDictionary等现有排序类,原因是SortedDictionary是依据Key排序,而这里是利用ADD的先后顺序来恒定顺序的。

越来越多IT相关资讯与技能文章,欢迎光临我的私房网站:http://www.zuowenjun.cn/

Post Author: admin

发表评论

电子邮件地址不会被公开。 必填项已用*标注