zoukankan      html  css  js  c++  java
  • .net WebServer示例及调用(接口WSDL动态调用 JAVA)

    新建.asmx页面

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Text;
    using System.Data;
    using System.Security.Cryptography;
    using System.Web.Script.Services;
    using System.IO;
    using System.Web.Script.Serialization;
    using DBUtility;
    using OAApp.Order;
    using System.IO.Compression;
    namespace OAApp
    {
        /// <summary>
        /// AppService 的摘要说明
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
        [System.Web.Script.Services.ScriptService]
        public class AppService : System.Web.Services.WebService
        {
           // string key = "";//钥匙
           // BLL.Hotels  hl= new BLL.Hotels()
            private readonly BLL.Hotels hl = new BLL.Hotels();
            private readonly BLL.hotelcollect hc = new BLL.hotelcollect();
            OAApp.TodayHY.HYModel.HY_iccard HY_iccard = new OAApp.TodayHY.HYModel.HY_iccard();
            OAApp.TodayHY.HYBLL.HY_iccard BB = new OAApp.TodayHY.HYBLL.HY_iccard();
    
            public static int[] EN_KEY = { 7, 2, 5, 4, 0, 1, 3, 6 };
            public static int[] DE_KEY = { 4, 5, 1, 6, 3, 2, 7, 0 };
    
            public static byte byteEncryption(byte nSrc)
            {
                byte nDst = 0;
                byte nBit = 0;
                int i;
                for (i = 0; i < 8; i++)
                {
                    nBit = (byte)(1 << EN_KEY[i]);
                    if ((nSrc & nBit) != 0)
                        nDst |= (byte)(1 << i);
                }
                return nDst;
            }
    
    
            public static byte byteDecryption(byte nSrc)
            {
                byte nDst = 0;
                byte nBit = 0;
                int i;
                for (i = 0; i < 8; i++)
                {
                    nBit = (byte)(1 << DE_KEY[i]);
                    if ((nSrc & nBit) != 0)
                        nDst |= (byte)(1 << i);
                }
                return nDst;
            }
    
            /// <summary>
            /// 加密
            /// </summary>
            /// <param name="source"></param>
            /// <returns></returns>
            public static string getCipherString(string source)
            {
                if (source.Trim() == "")
                {
                    return "";
                }
                string s = source;
                //byte[] sb = s.getBytes("UTF-8");
                byte[] sb = Encoding.UTF8.GetBytes(s);
                //String d = new String(sb, "UTF-8");
                string d = Encoding.UTF8.GetString(sb.ToArray());
                //sb = d.getBytes("UTF-8");
                sb = Encoding.UTF8.GetBytes(d);
                byte[] sbNew = new byte[sb.Length];
                StringBuilder sbb = new StringBuilder();
    
                for (int i = 0; i < sb.Length; i++)
                {
                    byte t = byteEncryption(sb[i]);
    
                    sbNew[i] = t;
                    char c = (char)t;
                    sbb.Append(c);
                }
    
                // String ss=new String(sbb.toString().getBytes("UTF-8"),"UTF-8");
                return sbb.ToString();
            }
    
            /// <summary>
            /// 解密
            /// </summary>
            /// <param name="cipherString"></param>
            /// <returns></returns>
            public static string Decrypt(string cipherString)
            {
                if (cipherString.Trim() == "")
                {
                    return "";
                }
                string drr = cipherString;
    
                byte[] drrByte = new byte[drr.Length];
                for (int i = 0; i < drrByte.Length; i++)
                {
                    //drrByte[i] = byteDecryption(Byte.valueOf((byte)drr.charAt(i)));
                    drrByte[i] = byteDecryption( Convert.ToByte(drr[i]));
                }
    
                //String des = new String(drrByte, "UTF-8");
                string des = Encoding.UTF8.GetString(drrByte.ToArray());
                return des;
            }
    
            public string StrJtextConte() 
            {
                string jtext = string.Empty;
    
                if ("POST" == System.Web.HttpContext.Current.Request.RequestType)
                {
                    System.IO.Stream sm = System.Web.HttpContext.Current.Request.InputStream;//获取post正文
                    int len = (int)sm.Length;//post数据长度
                    byte[] inputByts = new byte[len];//字节数据,用于存储post数据
                    sm.Read(inputByts, 0, len);//将post数据写入byte数组中
                    sm.Close();//关闭IO流
                    jtext = Encoding.GetEncoding("unicode").GetString(inputByts);//转为unicode编码
                    jtext = Server.UrlDecode(jtext);//下面解释一下Server.UrlDecode和Server.UrlEncode的作用
    
    
                }
                return jtext;
            }
    
            public string StrJtext() 
            {
                   string jtext = string.Empty;
    
                   if ("POST" == System.Web.HttpContext.Current.Request.RequestType)
                   {
                       System.IO.Stream sm = System.Web.HttpContext.Current.Request.InputStream;//获取post正文
                       int len = (int)sm.Length;//post数据长度
                       byte[] inputByts = new byte[len];//字节数据,用于存储post数据
                       sm.Read(inputByts, 0, len);//将post数据写入byte数组中
                       sm.Close();//关闭IO流
                       jtext = Encoding.Default.GetString(inputByts);//转为unicode编码
                       jtext = Server.UrlDecode(jtext);
                   }
                   return jtext;
            }
    
            #region  设备注册
            public struct ToJsonDeviceRegister
            {
                //属性的名字,必须与json格式字符串中的"key"值一样。
                public string deviceCode { get; set; }  //设备唯一编号
                public string deviceType { get; set; }//设备类型(0:安卓 1:iOS)
                public string appId { get; set; }//应用ID(2961256)
                public string userId { get; set; }//注册用户ID
                public string pushUserId { get; set; }//推送用户ID(百度生成)
                public string channelId { get; set; }//通道ID(百度)
                public string iosDeviceToken { get; set; }//设备令牌
    
            }
            /// <summary>
            /// 设备注册
            /// </summary>
            /// <param name="deviceCode">设备唯一编号</param>
            /// <param name="deviceType">设备类型(0:安卓 1:iOS)</param>
            /// <param name="appId">应用ID(2961256)</param>
            /// <param name="userId">注册用户ID</param>
            /// <param name="pushUserId">推送用户ID(百度生成)</param>
            /// <param name="channelId">通道ID(百度)</param>
            /// <param name="iosDeviceToken">设备令牌</param>
            /// <returns>正常:{"resCode":1, " resMsg":"正常"}异常:{"resCode":0," resMsg":"未知错误"}</returns>
            [WebMethod(Description = "设备注册")]
            public string DeviceRegister()
            {
                string jtext = StrJtext();//获取数据
                int res = 0;
                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                ToJsonDeviceRegister list = js.Deserialize<ToJsonDeviceRegister>(jtext);    //将json数据转化为对象类型并赋值给list
                string dCode = Decrypt(list.deviceCode);
                int dType = Convert.ToInt32(Decrypt(list.deviceType));
                string aoppid = Decrypt(list.appId);
                string userid = Decrypt(list.userId);
                string pushuserId = Decrypt(list.pushUserId);
                string channelid = Decrypt(list.channelId);
                string iosdevicetoken = Decrypt(list.iosDeviceToken);
                res= new BLL.deviceregister().AddDregisterInfo(dCode, dType, aoppid, userid, pushuserId, channelid, iosdevicetoken);
                return ReturnValue(res.ToString());
            }
            #endregion
    }
    #region  返回值
            public static string ReturnValue(string res)
            {
                StringBuilder JsonString = new StringBuilder();  
                if (Convert.ToInt32(res) > 0)
                {
                    JsonString.Append("{ ");
                    JsonString.Append(""resCode":");
                    JsonString.Append(""1",");
                    JsonString.Append(""resMsg":");
                    JsonString.Append(""正确"");
                    JsonString.Append("}");
                    return JsonString.ToString();
                }
                else
                {
                    JsonString.Append("{ ");
                    JsonString.Append(""resCode":");
                    JsonString.Append(""0",");
                    JsonString.Append(""resMsg":");
                    JsonString.Append(""未知错误"");
                    JsonString.Append("}");
                    return JsonString.ToString();
                }
            }
            #endregion
     #region  datatable 转json
        public static string CreateJsonParameters(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            //Exception Handling        
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append(""resCode":");
                JsonString.Append(""1",");
                JsonString.Append(""resMsg":");
                JsonString.Append(""正确",");
                JsonString.Append(""data":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + "",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + """ + dt.Rows[i][j].ToString() + """);
                        }
                    }
                    /**/
                    /**/
                    /**/
                    /*end Of String*/
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                JsonString.Append("{ ");
                JsonString.Append(""resCode":");
                JsonString.Append(""-4",");
                JsonString.Append(""resMsg":");
                JsonString.Append(""数据为空"");
                JsonString.Append("}");
                return JsonString.ToString();
            }
        }
        #endregion
    /*C#调用Web Servers 例*/
    protected void Page_Load(object sender, EventArgs e)
            {
                string result = BuildRequest("http://175.6.7.245:8007/AppService.asmx/UserMobileWebPayValidate", Server.UrlEncode("{"orderId":"wx444201411111611"}"), "UTF-8");
                Response.Write(result);
            }
            public static string BuildRequest(string strUrl, string strRequestData, string _input_charset)
            {
                Encoding code = Encoding.GetEncoding(_input_charset);
    
                //待请求参数数组字符串
                //string strRequestData = BuildRequestParaToString(sParaTemp, code);
    
                //把数组转换成流中所需字节数组类型
                byte[] bytesRequestData = code.GetBytes(strRequestData);
    
                //构造请求地址
                //string strUrl = GATEWAY_NEW + "_input_charset=" + _input_charset;
    
                //请求远程HTTP
                string strResult = "";
                try
                {
                    //设置HttpWebRequest基本信息
                    HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                    myReq.Method = "post";
                    myReq.ContentType = "application/x-www-form-urlencoded";
    
                    //填充POST数据
                    myReq.ContentLength = bytesRequestData.Length;
                    Stream requestStream = myReq.GetRequestStream();
                    requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                    requestStream.Close();
    
                    //发送POST数据请求服务器
                    HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                    Stream myStream = HttpWResp.GetResponseStream();
    
                    //获取服务器返回信息
                    StreamReader reader = new StreamReader(myStream, code);
                    StringBuilder responseData = new StringBuilder();
                    String line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        responseData.Append(line);
                    }
                    strResult = responseData.ToString();
    
                    //释放
                    myStream.Close();
                    reader.Close();
    
                    //服务器端返回的是一个XML格式的字符串,XML的Content才是我们所需要的Json数据
                    System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
                    xml.LoadXml(strResult);
                    strResult = xml.ChildNodes[1].InnerText;
                    //strResult = xml.LastChild.InnerText;
                }
                catch (Exception exp)
                {
                    strResult = "报错:" + exp.Message;
                }
    
                return strResult;
            }
    
            /// <summary>
            /// 其它方式
            /// </summary>
            /// <param name="methodName"></param>
            /// <param name="jsonParas"></param>
            /// <param name="_input_charset"></param>
            /// <returns></returns>
            public string Post(string methodName, string jsonParas, string _input_charset)
            {
                string Url = "http://175.6.7.245:8007/AppService.asmx";
                string strURL = Url + "/" + methodName;
    
                //创建一个HTTP请求  
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式  
                request.Method = "POST";
                //内容类型
                request.ContentType = "application/x-www-form-urlencoded";
    
                //设置参数,并进行URL编码  
                //虽然我们需要传递给服务器端的实际参数是JsonParas(格式:[{"UserID":"0206001","UserName":"ceshi"}]),
                //但是需要将该字符串参数构造成键值对的形式(注:"paramaters=[{"UserID":"0206001","UserName":"ceshi"}]"),
                //其中键paramaters为WebService接口函数的参数名,值为经过序列化的Json数据字符串
                //最后将字符串参数进行Url编码
                string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters");
                paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas);
    
                byte[] payload;
                //将Json字符串转化为字节  
                Encoding code = Encoding.GetEncoding(_input_charset);
                payload = code.GetBytes(paraUrlCoded);
                //设置请求的ContentLength   
                request.ContentLength = payload.Length;
                //发送请求,获得请求流  
    
                Stream writer;
                try
                {
                    writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
                }
                catch (Exception)
                {
                    writer = null;
                    Console.Write("连接服务器失败!");
                }
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                writer.Close();//关闭请求流
    
                String strValue = "";//strValue为http响应所返回的字符流
                HttpWebResponse response;
                try
                {
                    //获得响应流
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    response = ex.Response as HttpWebResponse;
                }
    
                Stream s = response.GetResponseStream();
    
                //服务器端返回的是一个XML格式的字符串,XML的Content才是我们所需要的Json数据
                XmlTextReader Reader = new XmlTextReader(s);
                Reader.MoveToContent();
                strValue = Reader.ReadInnerXml();//取出Content中的Json数据
                Reader.Close();
                s.Close();
    
                return strValue;//返回Json数据
            }

    接口WSDL动态调用

    /*WSDL或XML中 GetDataPortType为类名,getData为方法名*/    

    <wsdl:portType name="GetDataPortType">
            <wsdl:operation name="getData">
                <wsdl:input message="ns:getDataRequest" wsaw:Action="urn:getData"/>
                <wsdl:output message="ns:getDataResponse" wsaw:Action="urn:getDataResponse"/>
            </wsdl:operation>
        </wsdl:portType>
     public class WebServiceHelper
        {
            #region 动态调用WebService动态调用地址
            /// < summary>           
            /// 动态调用web服务         
            /// < /summary>          
            /// < param name="url">WSDL服务地址< /param> 
            /// < param name="methodname">方法名< /param>           
            /// < param name="args">参数< /param>           
            /// < returns>< /returns>          
            public static object InvokeWebService(string url, string methodname, object[] args)
            {
                return WebServiceHelper.InvokeWebService(url, null, methodname, args);
            }
            /// <summary>
            /// 动态调用web服务
            /// </summary>
            /// <param name="url">WSDL服务地址</param>
            /// <param name="classname">服务接口类名</param>
            /// <param name="methodname">方法名</param>
            /// <param name="args">参数值</param>
            /// <returns></returns>
            public static object InvokeWebService(string url, string classname, string methodname, object[] args)
            {
    
                string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
                if ((classname == null) || (classname == ""))
                {
                    classname = WebServiceHelper.GetWsClassName(url);
                }
                try
                {
    
                    //获取WSDL   
                    WebClient wc = new WebClient();
                    Stream stream = wc.OpenRead(url + "?wsdl");
                    ServiceDescription sd = ServiceDescription.Read(stream);
                    //注意classname一定要赋值获取 
                    classname = sd.Services[0].Name;
    
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);
    
                    //生成客户端代理类代码          
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);
                    CSharpCodeProvider icc = new CSharpCodeProvider();
    
    
                    //设定编译参数                 
                    CompilerParameters cplist = new CompilerParameters();
                    cplist.GenerateExecutable = false;
                    cplist.GenerateInMemory = true;
                    cplist.ReferencedAssemblies.Add("System.dll");
                    cplist.ReferencedAssemblies.Add("System.XML.dll");
                    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                    cplist.ReferencedAssemblies.Add("System.Data.dll");
                    //编译代理类                 
                    CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                    if (true == cr.Errors.HasErrors)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(System.Environment.NewLine);
                        }
                        throw new Exception(sb.ToString());
                    }
                    //生成代理实例,并调用方法                 
                    System.Reflection.Assembly assembly = cr.CompiledAssembly;
                    Type t = assembly.GetType(@namespace + "." + classname, true, true);
                    object obj = Activator.CreateInstance(t);
                    System.Reflection.MethodInfo mi = t.GetMethod(methodname);
                    return mi.Invoke(obj, args);
    
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
                    // return "Error:WebService调用错误!" + ex.Message;
                }
            }
            private static string GetWsClassName(string wsUrl)
            {
                string[] parts = wsUrl.Split('/');
                string[] pps = parts[parts.Length - 1].Split('.');
                return pps[0];
            }
            #endregion
        }
      #region 动态调用 webservices地址
    
                try
                {
                    object[] args = new object[3];
                    args[0] = (JsonHelper.GetJson<List<RealTimeData>>(listRealData));
                    args[1] = ("cnemcwater");
                    args[2] = ("cnemcwater");
    
                    object result = WebServiceHelper.InvokeWebService("http://172.0.0.1:8003/waterservice/services/GetData", "GetDataPortType",
                        "getData", args);
                    funcAddLog(result.ToString(), 0);
    
                }
    
                catch (Exception ex)
                {
                    funcAddLog(ex.ToString(), 0);
                    LogHelper.WriteLog("推送数据", ex);
                }
    
                #endregion
  • 相关阅读:
    工作中遇到的java 内存溢出,问题排查
    java线上内存溢出问题排查步骤
    性能测试-java内存溢出问题排查
    164 01 Android 零基础入门 03 Java常用工具类01 Java异常 04 使用try…catch…finally实现异常处理 04 终止finally执行的方法
    163 01 Android 零基础入门 03 Java常用工具类01 Java异常 04 使用try…catch…finally实现异常处理 03 使用多重catch结构处理异常
    162 01 Android 零基础入门 03 Java常用工具类01 Java异常 04 使用try…catch…finally实现异常处理 02 使用try-catch结构处理异常
    161 01 Android 零基础入门 03 Java常用工具类01 Java异常 04 使用try…catch…finally实现异常处理 01 try-catch-finally简介
    160 01 Android 零基础入门 03 Java常用工具类01 Java异常 03 异常处理简介 01 异常处理分类
    159 01 Android 零基础入门 03 Java常用工具类01 Java异常 02 异常概述 02 异常分类
    158 01 Android 零基础入门 03 Java常用工具类01 Java异常 02 异常概述 01 什么是异常?
  • 原文地址:https://www.cnblogs.com/elves/p/4235860.html
Copyright © 2011-2022 走看看