新建.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例的更多相关文章

  1. [C#] 图文解说调用WebServer实例

    本文旨在实现如何在.NET环境下调用WebServer,以天气接口为例进行说明. WebServer地址:http://www.webxml.com.cn/WebServices/WeatherWeb ...

  2. 【监控】WebServer入库与缓存更新代码优化小计

    问题描述: 通过WebServer将监控数据入库到Hbase,在入库之前需要将指标与ip的列表更新到缓存中,以便前台页面随时选择查看.前两天上了一些新用户导致负载增加,逐渐发现某些用户的监控场景出现丢 ...

  3. 面向新手的Webserver搭建(一)——IIS的搭建

    非常多童鞋说自己是做移动开发的,想挂个简单的Web API,但是server又不会搭,这样一来測试就成了问题.看看网上的教程.发现略难懂,并且大多是一个转一个,没价值,所以干脆写几篇文章讲讲简单的We ...

  4. 至Webserver构造svgz的文件需要http头,让你的浏览器中打开svgz档

    IE8以及IE8不支持以下浏览器SVG的.svgz它是svg压缩文件格公式,本文介绍的配置独立的浏览器,但浏览svgz请IE9+要么Firefox,Chrome和其他现代的浏览器打开. 让我们以正确显 ...

  5. 【COCOS2D-HTML5 开发之三】演示样例项目附源代码及执行的GIF效果图

    本站文章均为李华明Himi原创,转载务必在明显处注明:(作者新浪微博:@李华明Himi) 转载自[黑米GameDev街区] 原文链接: http://www.himigame.com/cocos2d- ...

  6. MapGuide应用程序演示样例——你好,MapGuide!

    图 3‑4显示了基于MapGuide的Web应用程序的开发流程,整个开发流程能够分为五个阶段.图中,矩形代表任务,椭圆形被任务使用的或被任务创建的实体,箭头代表数据流. 1) 载入文件类型的数据,配置 ...

  7. LwIP之socket应用--WebServer和Modbus TCP

    1. 引言 LwIP是嵌入式领域一个流行的以太网协议栈, LwIP开放源码,用C写成非常方便移植,并且支持socket接口,使用者可以集中精力处理应用功能. 本文就是LwIP socket使用的一个小 ...

  8. Libcurl的编译_HTTP/HTTPSclient源代码演示样例

    HTTP/HTTPSclient源代码演示样例 环境:  zlib-1.2.8  openssl-1.0.1g  curl-7.36 Author:  Kagula LastUpdateDate: 2 ...

  9. MapServer Tutorial——MapServer7.2.1教程学习——第一节用例实践:Example1.7 Adding a wms layer

    MapServer Tutorial——MapServer7.2.1教程学习——第一节用例实践:Example1.7 Adding a wms layer 前言 Add OGC WMS Layers( ...

随机推荐

  1. POJ2828 Buy Tickets[树状数组第k小值 倒序]

    Buy Tickets Time Limit: 4000MS   Memory Limit: 65536K Total Submissions: 19012   Accepted: 9442 Desc ...

  2. Ajax与JqueryUI和EasyUI错题总结

    Ajax与JqueryUI和EasyUI错题总结 正确答案A,解析:此题考察的是JQuery UI下的menu插件的使用,menu提供ui-state-disabled class 方法禁用任何菜单项 ...

  3. Fullscreen API 全屏显示网页

    可参考文档:http://blog.csdn.net/tywali/article/details/8623938 脚本代码 <script type="text/javascript ...

  4. JS文件加载:比较async和DOM Script

    async与script动态加载都能使文件异步加载,本文叙述它们对页面渲染和load加载的影响方面. 目前我用demo.js作为执行文件操作.代码: var now = function() { re ...

  5. bzoj 3163: [Heoi2013]Eden的新背包问题

    Description "寄没有地址的信,这样的情绪有种距离,你放着谁的歌曲,是怎样的心心静,能不能说给我听."失忆的Eden总想努力地回忆起过去,然而总是只能清晰地记得那种思念的 ...

  6. 再读《C++ Primer》——变量和基本类型

    刚上大学那时,几个室友一块买了本<C++ Primer>第4版,看了一遍后就没怎么碰了,偶尔拿出来翻翻,当作工具书使用.后来知道有第5版了,一直觉得内容差不多吧.直到最近,再读其中的一些内 ...

  7. WPF自适应可关闭的TabControl 类似浏览器的标签页

    效果如图: 虽然说是自适应可关闭的TabControl,但TabControl并不需要改动,不如叫自适应可关闭的TabItem. 大体思路:建一个用户控件,继承自TabItem,里面放个按钮,点击的时 ...

  8. MySQL配置、使用规范

    一.表名 和 数据库名 不要用大小写混合(即驼峰式),应该全部用小写,使用下划线作为连接符. Linux中表名默认区分大小写,Windows中默认不区分(全部转为小写),相互间的导入导出会有问题!! ...

  9. VIM编辑器常用命令

    一.剪切: 1. 欲从当前光标删除至下一个单词,请输入:dw  2. 欲从当前光标删除至当前行末尾,请输入:d$  3. 欲删除整行,请输入:dd //可以使用 dNd删除多行 N代表行数  4. 欲 ...

  10. 在eclipse中部署jsp项目

    昨天在做实验的时候发现图片的路径不对,怎么改都不对,后来想到在浏览器中输入localhost:8080是tomcat服务器的路径,没找到资源是不是就是项没有部署到tomcat中,去tomcat的web ...