码迷,mamicode.com
首页 > Web开发 > 详细

通过HttpWebRequest调用webService

时间:2017-04-28 23:44:17      阅读:305      评论:0      收藏:0      [点我收藏+]

标签:work   ide   address   serial   ring   etl   str   ssl   base   

调用远端接口关键方法如下:

        public object InsertAuditLog(string loginLog)
        {
              
            //Wsdlxml(loginLog)返回wsdl的xml
            byte[] bs = Encoding.UTF8.GetBytes(Wsdlxml(loginLog));
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://10.109.209.90:21010/gather/services/AioxPort");

            myRequest.Method = "POST";
            myRequest.ContentType = "text/xml; charset=utf-8";
            //mediate为调用方法
            myRequest.Headers.Add("SOAPAction", "http://tempuri.org/mediate");
            myRequest.ContentLength = bs.Length;

            //Console.WriteLine("完成准备工作");
            using (Stream reqStream = myRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                return sr.ReadToEnd();
                //Console.WriteLine("反馈结果" + responseString);
            }
            //Console.WriteLine("完成调用接口");
        }

Wsdlxml(loginLog)方法体如下(自己项目中的,仅参考用):

/// <summary>
        /// 拼装wsdl文件
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        public string Wsdlxml(string record)
        {
            string wsdl = string.Format(@"
                <?xml version=""1.0"" encoding=""UTF-8""?>
                <definitions
                    xmlns:soap=""http://schemas.xmlsoap.org/wsdl/soap/""
                    xmlns:tns=""http://www.asiainfo.com/web""
                    xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                    xmlns=""http://schemas.xmlsoap.org/wsdl/""
                    targetNamespace=""http://www.asiainfo.com/web""
                    name=""AioxService"">
                    <types></types>
                    <message name=""requestMessage"">
                        <part name=""textRecord"" type=""xsd:string"">{0}</part>
                        <part name=""reservedItem1"" type=""xsd:string""></part>
                        <part name=""reservedItem2"" type=""xsd:int"">{1}</part>
                    </message>
                    <message name=""responseMessage"">
                        <part name=""result"" type=""xsd:int""></part>
                    </message>
                    <portType name=""AioxPortType"">
                        <operation name=""mediate"" parameterOrder=""textRecord reservedItem1 reservedItem2"">
                            <input message=""tns:requestMessage""></input>
                            <output message=""tns:responseMessage""></output>
                        </operation>
                    </portType>
                    <binding name=""AioxPortBinding"" type=""tns:AioxPortType"">
                        <soap:binding transport=""http://schemas.xmlsoap.org/soap/http"" style=""rpc""></soap:binding>
                        <operation name=""mediate"">
                            <soap:operation soapAction=""mediate""></soap:operation>
                            <input>
                                <soap:body use=""literal"" namespace=""http://www.asiainfo.com/web""></soap:body>
                            </input>
                            <output>
                                <soap:body use=""literal"" namespace=""http://www.asiainfo.com/web""></soap:body>
                            </output>
                        </operation>
                    </binding>
                    <service name=""AioxService"">
                        <port name=""AioxPort"" binding=""tns:AioxPortBinding"">
                            <soap:address location=""http://10.109.209.90:21010/gather/services/AioxPort""></soap:address>
                        </port>
                    </service>
                </definitions>
                ", record, 21010);
            return wsdl;
        }

自己项目中的完整应用代码如下(备忘):

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using  System.Data;
using System.Collections;
using System.Xml;
using System.Net;
using System.IO;
using System.Text;

namespace AuditLog
{
    public class AuditLogServer
    {
        /// <summary>
        /// 将计件满足条件日志写入4A
        /// </summary>
        public void WriteAuditLogTo4A()
        {
            DateTime currTime = DateTime.Now;

            #region 处理登录日志
            DataTable loginLogList = GetLoginLog(currTime);
            string loginLog = Generate4ALogXmlForLogin(loginLogList);
            if (!string.IsNullOrEmpty(loginLog))
            {
                //调用写审计接口方法
                try
                {
                    InsertAuditLog(loginLog);
                }
                catch
                { }

                string updateSql = string.Format(@"update CC_LOGIN_HISTORY set tag=1 where LOGIN_TIME + 3 MINUTE > TIMESTAMP(REPLACE(‘{0}‘,‘/‘,‘-‘)) ", currTime);

                ExecuteNonQuery(updateSql);//修改已写入4a登录日志
                //处理模块操作日志
            }

            #endregion

            #region 处理模块操作日志

            string moduleLog = Generate4ALogXmlForModule(GetMoudelLog(currTime));
            if (!string.IsNullOrEmpty(moduleLog))
            {
                //调用写审计接口方法
                try
                {
                    var emd= InsertAuditLog(moduleLog);
                }
                catch { }

                string updateSql2 = string.Format(@"update CC_OPERATION_LOG set tag=1 where LOG_DATE + 3 MINUTE > TIMESTAMP(REPLACE(‘{0}‘,‘/‘,‘-‘)) ", currTime);
                ExecuteNonQuery(updateSql2);//修改已写入4a登录日志
            }
         
            #endregion
        }

        /// <summary>
        /// 向4a插入审计日志
        /// </summary>
        public object InsertAuditLog(string loginLog)
        {

            byte[] bs = Encoding.UTF8.GetBytes(Wsdlxml(loginLog));
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://10.109.209.90:21010/gather/services/AioxPort");

            myRequest.Method = "POST";
            myRequest.ContentType = "text/xml; charset=utf-8";
            myRequest.Headers.Add("SOAPAction", "http://tempuri.org/mediate");
            myRequest.ContentLength = bs.Length;

            //Console.WriteLine("完成准备工作");
            using (Stream reqStream = myRequest.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }

            using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
            {
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                return sr.ReadToEnd();
                //Console.WriteLine("反馈结果" + responseString);
            }
            //Console.WriteLine("完成调用接口");
        }

        #region 生成审计日志内容

        /// <summary>
        /// 生成登录操作日志内容
        /// </summary>
        public string Generate4ALogXmlForLogin(DataTable loginLogList)
        {
            string xml = "";
            if (loginLogList != null && loginLogList.Rows.Count > 0)
            {

                string itemXml = "";
                for (int i = 0; i < loginLogList.Rows.Count; i++)
                {
                    //调用插入4A审计日志
                    itemXml += string.Format(@"
                        <LOG4A>
                          <IDENTITY_NAME>4ABOSSLog</IDENTITY_NAME>
                          <RESOURCE_KIND>1</RESOURCE_KIND>
                          <RESOURCE_CODE>SCNGJJXC</RESOURCE_CODE>
                          <IDR_CREATION_TIME>{0}</IDR_CREATION_TIME>
                          <MAIN_ACCOUNT_NAME></MAIN_ACCOUNT_NAME>
                          <SUB_ACCOUNT_NAME>{1}</SUB_ACCOUNT_NAME>
                          <OPERATE_TIME>{2}</OPERATE_TIME>
                          <OP_TYPE_ID>1-KZYYT-10001</OP_TYPE_ID>
                          <OP_TYPE_NAME>登录</OP_TYPE_NAME>
                          <OP_LEVEL_ID>1</OP_LEVEL_ID>
                          <OPERATE_CONTENT>{3}</OPERATE_CONTENT>
                          <OPERATE_RESULT>0</OPERATE_RESULT>
                          <MODULE_ID>login</MODULE_ID>
                          <MODULE_NAME>登录模块</MODULE_NAME>
                          <TASK_CODE></TASK_CODE>
                          <BANKAPPROVE></BANKAPPROVE>
                          <BANKFLAG></BANKFLAG>
                          <CLIENT_NETWORK_ADDRESS>{4}</CLIENT_NETWORK_ADDRESS>
                          <CLIENT_NAME></CLIENT_NAME>
                          <CLIENT_ADDRESS>{5}</CLIENT_ADDRESS>
                          <CLIENT_PORT></CLIENT_PORT>
                          <CLIENT_MAC></CLIENT_MAC>
                          <CLIENT_CPU_SERIAL></CLIENT_CPU_SERIAL> 
                          <SERVER_ADDRESS>10.95.240.6</SERVER_ADDRESS>
                          <SERVER_PORT></SERVER_PORT>
                          <SERVER_MAC></SERVER_MAC>
                          <TO_PROVINCES_ID></TO_PROVINCES_ID>
                          <TO_PROVINCES_NAME></TO_PROVINCES_NAME>
                          <FROM_PROVINCES_ID></FROM_PROVINCES_ID>
                          <FROM_PROVINCES_NAME></FROM_PROVINCES_NAME> 
                        </LOG4A>
                        ", DateTime.Now, loginLogList.Rows[i]["SUB_ACCOUNT_NAME"].ToString(),
                         loginLogList.Rows[i]["OPERATE_TIME"].ToString(),
                          loginLogList.Rows[i]["OPERATE_CONTENT"].ToString(),
                           loginLogList.Rows[i]["CLIENT_NETWORK_ADDRESS"].ToString(),
                           loginLogList.Rows[i]["CLIENT_ADDRESS"].ToString());
                }
                xml = string.Format(@"
                    <?xml version=‘1.0‘ encoding=’UTF-8’?>
                    <ROOT>
                    {0}
                    </ROOT>
                    ", itemXml);
            }
            return xml;
        }

        /// <summary>
        /// 生成模块操作日志内容
        /// </summary>
        /// <param name="loginLogList"></param>
        /// <returns></returns>
        public string Generate4ALogXmlForModule(DataTable moduleLogList)
        {
            string xml = "";
            if (moduleLogList != null && moduleLogList.Rows.Count > 0)
            {

                string itemXml = "";
                for (int i = 0; i < moduleLogList.Rows.Count; i++)
                {
                    //调用插入4A审计日志
                    itemXml += string.Format(@"
                        <LOG4A>
                          <IDENTITY_NAME>4ABOSSLog</IDENTITY_NAME>
                          <RESOURCE_KIND>1</RESOURCE_KIND>
                          <RESOURCE_CODE>SCNGJJXC</RESOURCE_CODE>
                          <IDR_CREATION_TIME>{0}</IDR_CREATION_TIME>
                          <MAIN_ACCOUNT_NAME></MAIN_ACCOUNT_NAME>
                          <SUB_ACCOUNT_NAME>{1}</SUB_ACCOUNT_NAME>
                          <OPERATE_TIME>{2}</OPERATE_TIME>
                          <OP_TYPE_ID>1-KZYYT-10001</OP_TYPE_ID>
                          <OP_TYPE_NAME>登录</OP_TYPE_NAME>
                          <OP_LEVEL_ID>1</OP_LEVEL_ID>
                          <OPERATE_CONTENT>{3}</OPERATE_CONTENT>
                          <OPERATE_RESULT>0</OPERATE_RESULT>
                          <MODULE_ID>login</MODULE_ID>
                          <MODULE_NAME>登录模块</MODULE_NAME>
                          <TASK_CODE></TASK_CODE>
                          <BANKAPPROVE></BANKAPPROVE>
                          <BANKFLAG></BANKFLAG>
                          <CLIENT_NETWORK_ADDRESS></CLIENT_NETWORK_ADDRESS>
                          <CLIENT_NAME></CLIENT_NAME>
                          <CLIENT_ADDRESS></CLIENT_ADDRESS>
                          <CLIENT_PORT></CLIENT_PORT>
                          <CLIENT_MAC></CLIENT_MAC>
                          <CLIENT_CPU_SERIAL></CLIENT_CPU_SERIAL> 
                          <SERVER_ADDRESS>10.95.240.6</SERVER_ADDRESS>
                          <SERVER_PORT></SERVER_PORT>
                          <SERVER_MAC></SERVER_MAC>
                          <TO_PROVINCES_ID></TO_PROVINCES_ID>
                          <TO_PROVINCES_NAME></TO_PROVINCES_NAME>
                          <FROM_PROVINCES_ID></FROM_PROVINCES_ID>
                          <FROM_PROVINCES_NAME></FROM_PROVINCES_NAME> 
                        </LOG4A>
                        ", DateTime.Now, moduleLogList.Rows[i]["SUB_ACCOUNT_NAME"].ToString(),
                         moduleLogList.Rows[i]["OPERATE_TIME"].ToString(),
                          moduleLogList.Rows[i]["OPERATE_CONTENT"].ToString());
                }
                xml = string.Format(@"
                    <?xml version=‘1.0‘ encoding=’UTF-8’?>
                    <ROOT>
                    {0}
                    </ROOT>
                    ", itemXml);
            }
            return xml;
        }
        #endregion

        #region 数据库操作
        public DataTable ExcuteToTable(string sql)
        {
            //SqlConnection myConnection = new SqlConnection("server=(local);Integrated Security=SSPI;database=northwind");
            string sqlConn = "Database=jjxc;UID=jjxc_jk;PWD=bGWN=2R@";

            DataSet ds = Db2Helper.Helper_DB2.ExecuteDataset(sqlConn, System.Data.CommandType.Text, sql);

            return ds.Tables[0];
        }

        public int ExecuteNonQuery(string sql)
        {
            string sqlConn = "Database=jjxc;UID=jjxc_jk;PWD=bGWN=2R@";

            return Db2Helper.Helper_DB2.ExecuteNonQuery(sqlConn, System.Data.CommandType.Text, sql);
        }
        #endregion

        #region 查询满足审计的日志sql

        /// <summary>
        /// 获取满足条件的登录日志
        /// </summary>
        /// <returns></returns>
        public DataTable GetLoginLog(DateTime currTime)
        {

            //获取最近3分钟登录信息
            string sql = string.Format(@"SELECT    ‘<![CDATA[登录:用户名=‘
                       || TRIM (B.NAME)
                       || ‘,工号=‘
                       || B.LOGIN_NAME
                       || ‘,登录时间=‘
                       || TO_CHAR (A.LOGIN_TIME, ‘YYYY-MM-DD HH24:MI:SS‘)
                       || ‘,登录系统=计件系统,登录IP=‘
                       || A.LOGIN_HOST
                       || ‘]]>‘
                          OPERATE_CONTENT,
                       A.LOGIN_TIME OPERATE_TIME,
                       B.LOGIN_NAME SUB_ACCOUNT_NAME,
                       A.LOGIN_HOST CLIENT_NETWORK_ADDRESS,
                       A.LOGIN_HOST CLIENT_ADDRESS
                  FROM CC_LOGIN_HISTORY A, CC_USER B
                 WHERE     A.USER_ID = B.ID
                       AND A.LOGIN_TIME + 3 MINUTE > TIMESTAMP(REPLACE(‘{0}‘,‘/‘,‘-‘)) 
                       AND A.TAG IS NULL", currTime);
            return ExcuteToTable(sql);
        }
        /// <summary>
        /// 获取满足条件的模块操作日志
        /// </summary>
        /// <returns></returns>
        public DataTable GetMoudelLog(DateTime currTime)
        {
            string sql = string.Format(@"
                SELECT LOGIN_NAME SUB_ACCOUNT_NAME,
                       LOG_DATE OPERATE_TIME,
                          ‘<![CDATA[模块操作:用户名=‘
                       || TRIM (USER_NAME)
                       || ‘,工号=‘
                       || LOGIN_NAME
                       || ‘,操作时间=‘
                       || TO_CHAR (LOG_DATE, ‘YYYY-MM-DD HH24:MI:SS‘)
                       || ‘,登录系统=计件系统,内容=‘
                       || PERMISSION
                       || ‘||‘
                       || DESCRIPTION
                       || ‘]]>‘
                          OPERATE_CONTENT
                  FROM CC_OPERATION_LOG
                 WHERE LOG_DATE + 3 MINUTE >  TIMESTAMP(REPLACE(‘{0}‘,‘/‘,‘-‘))  AND TAG IS NULL
                ", currTime);
            return ExcuteToTable(sql);
        }
        #endregion
        
        /// <summary>
        /// 拼装wsdl文件
        /// </summary>
        /// <param name="record"></param>
        /// <returns></returns>
        public string Wsdlxml(string record)
        {
            string wsdl = string.Format(@"
                <?xml version=""1.0"" encoding=""UTF-8""?>
                <definitions
                    xmlns:soap=""http://schemas.xmlsoap.org/wsdl/soap/""
                    xmlns:tns=""http://www.asiainfo.com/web""
                    xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
                    xmlns=""http://schemas.xmlsoap.org/wsdl/""
                    targetNamespace=""http://www.asiainfo.com/web""
                    name=""AioxService"">
                    <types></types>
                    <message name=""requestMessage"">
                        <part name=""textRecord"" type=""xsd:string"">{0}</part>
                        <part name=""reservedItem1"" type=""xsd:string""></part>
                        <part name=""reservedItem2"" type=""xsd:int"">{1}</part>
                    </message>
                    <message name=""responseMessage"">
                        <part name=""result"" type=""xsd:int""></part>
                    </message>
                    <portType name=""AioxPortType"">
                        <operation name=""mediate"" parameterOrder=""textRecord reservedItem1 reservedItem2"">
                            <input message=""tns:requestMessage""></input>
                            <output message=""tns:responseMessage""></output>
                        </operation>
                    </portType>
                    <binding name=""AioxPortBinding"" type=""tns:AioxPortType"">
                        <soap:binding transport=""http://schemas.xmlsoap.org/soap/http"" style=""rpc""></soap:binding>
                        <operation name=""mediate"">
                            <soap:operation soapAction=""mediate""></soap:operation>
                            <input>
                                <soap:body use=""literal"" namespace=""http://www.asiainfo.com/web""></soap:body>
                            </input>
                            <output>
                                <soap:body use=""literal"" namespace=""http://www.asiainfo.com/web""></soap:body>
                            </output>
                        </operation>
                    </binding>
                    <service name=""AioxService"">
                        <port name=""AioxPort"" binding=""tns:AioxPortBinding"">
                            <soap:address location=""http://10.109.209.90:21010/gather/services/AioxPort""></soap:address>
                        </port>
                    </service>
                </definitions>
                ", record, 21010);
            return wsdl;
        }
    }
}
View Code

参考网址:

通过HttpWebRequest在后台对WebService进行调用

C# HttpWebRequest 绝技

C#HttpHelper类

通过HttpWebRequest调用webService

标签:work   ide   address   serial   ring   etl   str   ssl   base   

原文地址:http://www.cnblogs.com/senyier/p/6783555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!