新建.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 = { , , , , , , , };
public static int[] DE_KEY = { , , , , , , , }; public static byte byteEncryption(byte nSrc)
{
byte nDst = ;
byte nBit = ;
int i;
for (i = ; i < ; i++)
{
nBit = (byte)( << EN_KEY[i]);
if ((nSrc & nBit) != )
nDst |= (byte)( << i);
}
return nDst;
} public static byte byteDecryption(byte nSrc)
{
byte nDst = ;
byte nBit = ;
int i;
for (i = ; i < ; i++)
{
nBit = (byte)( << DE_KEY[i]);
if ((nSrc & nBit) != )
nDst |= (byte)( << 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 = ; 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 = ; 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, , 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, , 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 = ;
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) > )
{
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 > )
{
JsonString.Append("{ ");
JsonString.Append("\"resCode\":");
JsonString.Append("\"1\",");
JsonString.Append("\"resMsg\":");
JsonString.Append("\"正确\",");
JsonString.Append("\"data\":[ ");
for (int i = ; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = ; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
}
else if (j == dt.Columns.Count - )
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
}
}
/**/
/**/
/**/
/*end Of String*/
if (i == dt.Rows.Count - )
{
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, , 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[].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, , 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[].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 - ].Split('.');
return pps[];
}
#endregion
}
  #region 动态调用 webservices地址

            try
{
object[] args = new object[];
args[] = (JsonHelper.GetJson<List<RealTimeData>>(listRealData));
args[] = ("cnemcwater");
args[] = ("cnemcwater"); object result = WebServiceHelper.InvokeWebService("http://172.0.0.1:8003/waterservice/services/GetData", "GetDataPortType",
"getData", args);
funcAddLog(result.ToString(), ); } catch (Exception ex)
{
funcAddLog(ex.ToString(), );
LogHelper.WriteLog("推送数据", ex);
} #endregion

.net WebServer示例及调用(接口WSDL动态调用 JAVA)的更多相关文章

  1. C#调用WebService服务(动态调用)

    原文:C#调用WebService服务(动态调用) 1 创建WebService using System; using System.Web.Services; namespace WebServi ...

  2. 使用接口的方式调用远程服务 ------ 利用动态调用服务,实现.net下类似Dubbo的玩法。

    分布式微服务现在成为了很多公司架构首先项,据我了解,很多java公司架构都是 Maven+Dubbo+Zookeeper基础上扩展的. Dubbo是Alibaba开源的分布式服务框架,它最大的特点是按 ...

  3. SOA 下实现分布式 调用 cxf+ webService +动态调用

    近期项目间隙 自学了  webservice   一下 是我写的  一个demo 首先我们在web.xml 里配置如下 <servlet> <servlet-name>CXFS ...

  4. asp.net使用wsdl文件调用接口,以及调用SSL接口报错“根据验证过程 远程证书无效”的处理

    1.调用wsdl接口,首先需要将wsdl文件转换为cs文件: 进入VS 开发人员命令提示行,输入如下命令: c:/Program Files/Microsoft Visual Studio 8/VC& ...

  5. c# 动态调用.net编写的webservices接口

    创建类WebServiceHelper: public class WebServiceHelper { #region 动态调用WebService动态调用地址 /// < summary&g ...

  6. Delphi 类库(DLL)动态调用与静态调用示例讲解

    在Delphi或者其它程序中我们经常需要调用别人写好的DLL类库,下面直接上示例代码演示如何进行动态和静态的调用方法: { ************************************** ...

  7. C#程序实现动态调用DLL的研究(转)

    摘 要:在<csdn开发高手>2004年第03期中的<化功大法——将DLL嵌入EXE>一文,介绍了如何把一个动态链接库作为一个资源嵌入到可执行文件,在可执行文件运行时,自动从资 ...

  8. C# .NET 动态调用webservice的三种方式

    转载自 百度文库 http://wenku.baidu.com/link?url=Q2q50wohf5W6UX44zqotXFEe_XOMaib4UtI3BigaNwipOHKNETloMF4ax4W ...

  9. C#程序实现动态调用DLL的研究[转]

    摘   要: 在< csdn 开发高手> 2004 年第 03 期中的<化功大法——将 DLL 嵌入 EXE >一文,介绍了如何把一个动态链接库作为一个资源嵌入到可执行文件,在 ...

随机推荐

  1. 廖雪峰Java10加密与安全-5签名算法-1RSA签名算法

    1.数字签名 甲在发送加密消息的时候,还要发送自己的签名,而这个签名是用甲的privateKey计算的:而乙要验证这个签名是否是合法的,会用甲的publicKey去验证,如果验证成功,这个消息确实是甲 ...

  2. windows下 将tomcat做成服务,并于oracle后启动

    一.将tomcat做成服务 1.下载解压版的tomcat 6.*, 设置java.tomcat的环境(这个就不说了). 2.运行->cmd->到tomcat安装目录的bin目录: 3.运行 ...

  3. 解决 Error retrieving parent for item: No resource found that matches the given name 'Theme.AppCompat.Light.DarkActionBar'

    If you are looking for the solution in Android Studio : Right click on your app Open Module Settings ...

  4. PAT甲级——A1035 Password

    To prepare for PAT, the judge sometimes has to generate random passwords for the users. The problem ...

  5. 从登录接口的响应结果里提取token

    token一般存在于2个地方:1. cookie, 2 ,某个接口的响应结果中 1. 我们接口的token存在于登录接口的响应结果中,如下图: token值 为红色标记的值,在登录接口里加以下2行代码 ...

  6. 作业test

    views Car <template> <div class="car"> <Nav/> <div class="wrap&q ...

  7. Eureka配置问题

    在使用Spring Cloud做微服务开发中,经常会使用Eureka Server作为注册中心,如果配置不当可能会导致一些不可预期的异常信息.以下是我最近遇到的因为忽略了配置eureka.client ...

  8. 2019-4-17-从-dotnet-core-3.0-的特性让-WPF-布局失效讨论-API-兼容

    title author date CreateTime categories 从 dotnet core 3.0 的特性让 WPF 布局失效讨论 API 兼容 lindexi 2019-4-17 1 ...

  9. 其他pyton笔记

    #小部分老男孩pyton课程 #所有脚本第一句话都要写解释以下脚本是用什么解释器 #!/usr/bin/env python #语言设置为:简体中文 #_*_coding:utf-8_*_ ##### ...

  10. vue的事件绑定

    vue事件有两方面内容:DOM事件 和 自定义事件. DOM事件 vue中采用DOM2级事件的处理方式,为IE9以上的浏览器服务.下面我们先来讲解一下什么是DOM2级事件吧! JS中DOM0级事件有两 ...