zoukankan      html  css  js  c++  java
  • 通过HttpWebRequest调用webService

    调用远端接口,向远端接口写入一个xml文件(loginLog为xml的字符串)。关键方法如下:

            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("完成调用接口");
            }

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

    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 处理登录日志
    
                string loginLog = "";
                DataTable loginLogList = GetLoginLog(currTime);
                if (loginLogList != null && loginLogList.Rows.Count > 0)
                {
                    for (int i = 0; i < loginLogList.Rows.Count; i++)
                    {
                        DataRow dr = loginLogList.Rows[i];
                        //生成一条日志
                        loginLog = Generate4ALogXml(dr,1);
                        try
                        {
                            InsertAuditLog(loginLog);
                            string updateSql = string.Format(@"update CC_LOGIN_HISTORY set tag=1 where ID={0}", Convert.ToInt32(dr["ID"].ToString()));
                            ExecuteNonQuery(updateSql);//修改已写入4a登录日志
                        }
                        catch { }
    
                        //if (i > 1)
                        //{
                        //    loginLogList = null;
                        //    break;
                        //}
                    }
                }
                #endregion
    
                #region 处理模块操作日志
                string moduleLog = "";
                DataTable moduleLogList = GetMoudelLog(currTime);
                if (moduleLogList != null && moduleLogList.Rows.Count > 0)
                {
                    for (int i = 0; i < moduleLogList.Rows.Count; i++)
                    {
                        DataRow dr = moduleLogList.Rows[i];
                        moduleLog = Generate4ALogXml(dr, 2);
                        try
                        {
                            InsertAuditLog(moduleLog);
                            string updateSql = string.Format(@"update CC_OPERATION_LOG set tag=1 where ID={0}", Convert.ToInt32(dr["ID"].ToString()));
                            ExecuteNonQuery(updateSql);//修改已写入4a登录日志
                        }
                        catch { }
    
                        //if (i > 1)
                        //{
                        //    moduleLogList = null;
                        //    break;
                        //}
                    }
                }
    
                #endregion
            }
    
            /// <summary>
            /// 向4a插入审计日志
            /// </summary>
            public object InsertAuditLog(string loginLog)
            {
    
                //byte[] bs = Encoding.UTF8.GetBytes(Wsdlxml(loginLog));
                byte[] bs = Encoding.UTF8.GetBytes(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);
                    var rs = sr.ReadToEnd();
                    return rs;
                    //Console.WriteLine("反馈结果" + responseString);
                }
                //Console.WriteLine("完成调用接口");
            }
    
            #region 生成审计日志内容
    
            /// <summary>
            /// 生成日志内容
            /// </summary>
            /// <param name="dr">表格的行</param>
            /// <param name="opType">操作类型1=登录 2=模块操作</param>
            /// <returns></returns>
            public string Generate4ALogXml(DataRow dr, int opType)
            {
                string opTypeName = "";
                string moduleName = "";
    
                string clientNetAddr = "";
                string clientAddr = "";
    
                if (opType == 1)//登录
                {
                    opTypeName = "登录";
                    moduleName = "登录模块";
                    clientNetAddr = dr["CLIENT_NETWORK_ADDRESS"].ToString();
                    clientAddr = dr["CLIENT_ADDRESS"].ToString();
                }
                else if (opType == 2)//模块操作
                {
                    opTypeName = "模块操作";
                    moduleName = dr["PERMISSION"].ToString();
                    clientNetAddr = dr["CLIENT_NETWORK_ADDRESS"].ToString();
                    clientAddr = dr["CLIENT_ADDRESS"].ToString();
                }
    
                string xml = "";
                string 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>{6}</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>{7}</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.ToString("yyyy-MM-dd hh:mm:ss"), 
                dr["SUB_ACCOUNT_NAME"].ToString(),
                dr["OPERATE_TIME"].ToString().Replace("/", "-"),
                dr["OPERATE_CONTENT"].ToString(),
                clientNetAddr,
                clientAddr, 
                opTypeName, moduleName);
    
                xml = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?><ROOT>{0}</ROOT>", itemXml);
                return xml;
            }
    
            #endregion
    
            #region 查询满足审计的日志sql
    
            /// <summary>
            /// 获取满足条件的登录日志
            /// </summary>
            /// <returns></returns>
            public DataTable GetLoginLog(DateTime currTime)
            {
                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.ID,
                                       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,JJXCNO_FOR_4A C
                                 WHERE     A.USER_ID = B.ID
                                       AND A.LOGIN_TIME  > TIMESTAMP('2017-6-1 0:00:00')  
                                       AND A.TAG IS NULL
                                       AND C.NO_JJXC=B.LOGIN_NAME");
                return ExcuteToTable(sql);
            }
            /// <summary>
            /// 获取满足条件的模块操作日志
            /// </summary>
            /// <returns></returns>
            public DataTable GetMoudelLog(DateTime currTime)
            {
                string sql = string.Format(@"
                                SELECT A.*, CLIENT_NETWORK_ADDRESS, CLIENT_ADDRESS
      FROM (SELECT A.ID,
                   A.LOGIN_NAME,
                   A.LOGIN_NAME SUB_ACCOUNT_NAME,
                   A.PERMISSION,
                   A.LOG_DATE OPERATE_TIME,
                      '<![CDATA[模块操作:用户名='
                   || TRIM (A.USER_NAME)
                   || ',工号='
                   || A.LOGIN_NAME
                   || ',操作时间='
                   || TO_CHAR (A.LOG_DATE, 'YYYY-MM-DD HH24:MI:SS')
                   || ',操作系统=计件系统,内容='
                   || A.PERMISSION
                   || '||'
                   || A.DESCRIPTION
                   || ']]>'
                      OPERATE_CONTENT
              FROM CC_OPERATION_LOG A, JJXCNO_FOR_4A B
             WHERE     A.TAG IS NULL
                   AND A.LOG_DATE > TIMESTAMP ('2017-6-1 0:00:00')
                   AND B.NO_JJXC = A.LOGIN_NAME) A
           LEFT JOIN
           (SELECT *
              FROM (SELECT BB.*,
                           ROW_NUMBER ()
                              OVER (PARTITION BY BB.LOGIN_TIME, BB.LOGIN_NAME)
                              AS NUM
                      FROM (SELECT TO_CHAR (LOGIN_TIME, 'YYYY-MM-DD') LOGIN_TIME,
                                   B.LOGIN_NAME,
                                   AA.LOGIN_HOST CLIENT_NETWORK_ADDRESS,
                                   AA.LOGIN_HOST CLIENT_ADDRESS
                              FROM CC_LOGIN_HISTORY AA, CC_USER B
                             WHERE     AA.USER_ID = B.ID
                                   AND AA.LOGIN_TIME >
                                          TIMESTAMP ('2017-6-1 0:00:00')) BB)
             WHERE NUM = 1) B
              ON (    TO_CHAR (A.OPERATE_TIME, 'YYYY-MM-DD') = B.LOGIN_TIME
                  AND A.LOGIN_NAME = B.LOGIN_NAME)");
                return ExcuteToTable(sql);
            }
            #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
        }
    }
    View Code

    参考网址:

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

    C# HttpWebRequest 绝技

    C#HttpHelper类

  • 相关阅读:
    物料序号不可修改
    物料序号不可输入
    禁用物料不允许BOM
    MRP工作台任务下达之x组织屏蔽全部发放功能
    MRP工作台任务下达之计划组为必输
    按计划员自动带出对应任务类型
    java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource解决方法
    web.xml 中<taglib>报错(转载)
    web.xml元素介绍
    Struts+Tomcat搭建
  • 原文地址:https://www.cnblogs.com/senyier/p/6783555.html
Copyright © 2011-2022 走看看