基于Web Service的客户端框架搭建三:代理层(Proxy)
前言
代理层的主要工作是调用Web Service,将在FCL层序列化好的Json数据字符串Post到Web Service,然后获得Reponse,再从响应流中读取到调用结果Json字符串,在Dispatcher反序列化成数据对象,在UI层呈现出来。
HttpHelper类(参考自:http://blog.csdn.net/eriloan/article/details/7000790)
刚开始是直接在Proxy类中直接写的Post方法,后来看到这篇帖子,将Http相关的部分封装成了工具类HttpHelper。原帖中还包含了使用TCPSocket发送请求调用WebService的内容。
namespace ProjectmsMGT_Proxy
{
public class HttpHelper
{
/// <summary>
/// Http请求URL
/// </summary>
public string Url { set; get; } /// <summary>
/// 请求参数Key(约定服务方法参数名同名)
/// 在使用Post方式向服务器端发送请求的时候,请求数据中包含了参数部分,参数部分我们需要告诉WebService接口方法,实参要传给的接口方法行参名,由RequestParaKey指定
/// 当然当接口方法有多个形参时,就不建议单独设计这样一个属性,直接在sendMsg中添加,此处只是为了突出RequestParaKey的重要性
/// </summary>
public string RequestParaKey { set; get; } /// <summary>
/// 证书文件路径
/// </summary>
public string CertificateFilePath { set; get; } /// <summary>
/// 证书文件口令
/// </summary>
public string CertificateFilePwd { set; get; } /// <summary>
/// 构造函数,不使用证书
/// </summary>
/// <param name="url"></param>
/// <param name="requestParaKey"></param>
public HttpHelper(string url, string requestParaKey)
{
this.Url = url;
this.RequestParaKey = requestParaKey;
} /// <summary>
/// 构造函数,使用证书
/// </summary>
/// <param name="url"></param>
/// <param name="requestParaKey"></param>
/// <param name="certFilePath"></param>
/// <param name="certFilePwd"></param>
public HttpHelper(string url, string requestParaKey, string certFilePath, string certFilePwd)
{
this.Url = url;
this.RequestParaKey = requestParaKey;
this.CertificateFilePath = certFilePath;
this.CertificateFilePwd = certFilePwd;
} /// <summary>
/// 使用Get方式,发送Http请求
/// </summary>
/// <param name="methodName">所请求的接口方法名</param>
/// <param name="isLoadCert">是否加载证书</param>
/// <returns>响应字符串</returns>
public string CreateHttpGet(string methodName, bool isLoadCert)
{
HttpWebRequest request = CreateHttpRequest(methodName, @"GET", isLoadCert); return CreateHttpResponse(request);
} /// <summary>
/// 使用Post方式,发送Http请求
/// </summary>
/// <param name="methodName">所请求的接口方法名</param>
/// <param name="sendMsg">请求参数(不包含RequestParaKey部分)</param>
/// <param name="isLoadCert">是否加载证书</param>
/// <returns>响应字符串</returns>
public string CreateHttpPost(string methodName, string sendMsg, bool isLoadCert)
{
//创建Http请求
HttpWebRequest request = CreateHttpRequest(methodName, @"POST", isLoadCert);
if (null != sendMsg && !"".Equals(sendMsg))
{
//添加请求参数
AddHttpRequestParams(request, sendMsg);
} //获得响应
return CreateHttpResponse(request);
} /// <summary>
/// 将请求参数写入请求流
/// </summary>
/// <param name="request"></param>
/// <param name="sendMsg"></param>
private void AddHttpRequestParams(HttpWebRequest request, string sendMsg)
{
//将请求参数进行URL编码
string paraUrlCoded = System.Web.HttpUtility.UrlEncode(RequestParaKey) + "=" +
System.Web.HttpUtility.UrlEncode(sendMsg); byte[] data = Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = data.Length;
Stream requestStream = null;
using (requestStream = request.GetRequestStream())
{
//将请求参数写入流
requestStream.Write(data, , data.Length);
} requestStream.Close();
} /// <summary>
/// 创建HttpRequest
/// </summary>
/// <param name="methodName"></param>
/// <param name="requestType">POST或者GET</param>
/// <param name="isLoadCert"></param>
/// <returns>HttpWebRequest对象</returns>
private HttpWebRequest CreateHttpRequest(string methodName, string requestType, bool isLoadCert)
{
HttpWebRequest request = null;
try
{
string requestUriString = Url + "/" + methodName;
request = (HttpWebRequest)WebRequest.Create(requestUriString);
if (isLoadCert)
{
//创建证书
X509Certificate2 cert = CreateX509Certificate2();
//添加证书认证
request.ClientCertificates.Add(cert);
}
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = requestType;
}
catch (Exception)
{
//Console.WriteLine("创建HttpRequest失败。原因:" + e.Message);
request = null;
} return request;
} /// <summary>
/// 创建请求响应
/// </summary>
/// <param name="request"></param>
/// <returns>响应字符串</returns>
private string CreateHttpResponse(HttpWebRequest request)
{
String str;
HttpWebResponse response = null;
Stream responseStream = null;
XmlTextReader responseReader = null;
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
//获得响应流
responseStream = response.GetResponseStream();
responseReader = new XmlTextReader(responseStream);
responseReader.MoveToContent();
str = responseReader.ReadInnerXml();
}
}
catch (Exception e)
{
str = "[{\"Rescode\":\"0\",\"Resmsg\":\"通信失败。原因:" + e.Message + "\"}]";
}
finally
{
if (null != response)
{
responseReader.Close();
responseStream.Close();
response.Close();
}
} return str;
} /// <summary>
/// 创建证书
/// </summary>
/// <returns>X509Certificate2对象</returns>
private X509Certificate2 CreateX509Certificate2()
{
X509Certificate2 cert = null;
try
{
cert = new X509Certificate2(CertificateFilePath, CertificateFilePwd);
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(ServerCertificateValidationCallback);
}
catch (Exception)
{
//Console.WriteLine("创建X509Certificate2失败。原因:" + e.Message);
cert = null;
}
return cert;
} /// <summary>
/// Verifies the remote Secure Sockets Layer (SSL) certificate used for authentication
/// </summary>
/// <param name="obj">An object that contains state information for this validation</param>
/// <param name="cer">The certificate used to authenticate the remote party</param>
/// <param name="chain">The chain of certificate authorities associated with the remote certificate</param>
/// <param name="error">One or more errors associated with the remote certificate</param>
/// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication</returns>
private bool ServerCertificateValidationCallback(object obj, X509Certificate cer, X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
return true;
}
}
}
HttpHelper中把SSL证书的部分也包含进来,但是证书认证机制部分ServerCertificateValidationCallback还没设计,各位大神可以自行发挥。
代理类Proxy
有了HttpHelper之后,代理类的代码就比较明了了。
namespace ProjectmsMGT_Proxy
{
public class ProjectmsProxy
{
private readonly string Url = "http://59.68.29.106:8087/IFT_Project.asmx";//通过配置文件获取Web Service地址
private readonly string requestParaKey = "paramaters";//服务端所有接口函数统一的参数名
private HttpHelper httpHelper; public ProjectmsProxy()
{
//初始化
Initialize();
} private void Initialize()
{
httpHelper = new HttpHelper(this.Url, this.requestParaKey);
} /// <summary>
/// 使用Get方式调用WebService,不带参数
/// </summary>
/// <param name="methodName"></param>
/// <param name="parasJsonStr"></param>
/// <param name="requestType"></param>
/// <returns></returns>
public string Excute(string methodName, string parasJsonStr, string requestType)
{
return httpHelper.CreateHttpGet(methodName, false);
} /// <summary>
/// 默认使用Post方式调用WebService,带参数
/// </summary>
/// <param name="methodName"></param>
/// <param name="parasJsonStr"></param>
/// <returns></returns>
public string Excute(string methodName, string parasJsonStr)
{
return httpHelper.CreateHttpPost(methodName, parasJsonStr, false);
} /// <summary>
/// 默认使用Post方式调用WebService,不带参数
/// </summary>
/// <param name="methodName"></param>
/// <returns></returns>
public string Excute(string methodName)
{
return httpHelper.CreateHttpPost(methodName, null, false);
}
}
}
Proxy中重载了Excute方法,三个参数的表示使用Get方式调用WebService(因为不建议在Get方式下传参给Web Service),两个参数和一个参数的Excute默认是使用Post方式带参数和不带参数的情况。
总结
将方法名作为参数Post到Web Service可以减少很多重复代码,不需要对服务端的每个接口函数做写一个代理函数,这是使用Post方式比使用添加Web服务引用方式更加灵活。
基于Web Service的客户端框架搭建三:代理层(Proxy)的更多相关文章
- 基于Web Service的客户端框架搭建四:终结篇
前言 这是这个系列的终结篇,前面3个博客介绍了一下内容: 1.使用Http Post方式调用Web Service 2.客户端框架之数据转换层 3.客户端框架之代理层 框架结构 框架是基于C#的,在V ...
- 基于Web Service的客户端框架搭建二:数据转换层(FCL)
引言 要使用WebService来分离客户端与服务端,必定要使用约定好两者之间的数据契约.Json数据以其完全独立于语言的优势,成为开发者的首选.C# JavaScriptSerializer为Jso ...
- 基于Web Service的客户端框架搭建一:C#使用Http Post方式传递Json数据字符串调用Web Service
引言 前段时间一直在做一个ERP系统,随着系统功能的完善,客户端(CS模式)变得越来越臃肿.现在想将业务逻辑层以下部分和界面层分离,使用Web Service来做.由于C#中通过直接添加引用的方来调用 ...
- 基于JavaScript的REST客户端框架
现在REST是一个比较热门的概念,REST已经成为一个在Web上越来越常用的应用,基于REST的Web服务越来越多,包括Twitter在内的微博客都是用REST做为对外的API,先前我曾经介绍过“基于 ...
- 《基于 Web Service 的学分制教务管理系统的研究与实现》论文笔记(十一)
标题:基于 Web Service 的学分制教务管理系统的研究与实现 一.基本内容 时间:2014 来源:苏州大学 关键词:: 教务管理系统 学分制 Web Service 二.研究内容 1.教务管理 ...
- 基于Docker的TensorFlow机器学习框架搭建和实例源码解读
概述:基于Docker的TensorFlow机器学习框架搭建和实例源码解读,TensorFlow作为最火热的机器学习框架之一,Docker是的容器,可以很好的结合起来,为机器学习或者科研人员提供便捷的 ...
- MyEclipse构建Web Service(Xfire框架)
以下是本人原创,如若转载和使用请注明转载地址.本博客信息切勿用于商业,可以个人使用,若喜欢我的博客,请关注我,谢谢!博客地址 任务要求: 使用Xfire实现一个简单的CalculatorWebServ ...
- JAVA开发Web Service几种框架介绍
郑重声明:此文为转载来的,出处已不知了,侵告删. 在讲Web Service开发服务时,需要介绍一个目前开发Web Service的几个框架,分别为Axis,axis2,Xfire,CXF以及JWS( ...
- SOAP: java+xfire(web service) + php客户端
作者: 吴俊杰 web service这项技术暂不说它有多落伍,但是项目中用到了,没法逃避! xml和json各有各的好处,但是JSON无疑是当今数据交互的主流了.客户soap服务器端用的是 j ...
随机推荐
- 位图bitbucket
问题:假设有500w条数据,数据是在2^32-1的范围内,数据重复,如何减少内存对数字进行统计呢? 如果用字典来标记数字是否已经统计过来,数字做为key, value仅为0 or1,那么这样需要消耗 ...
- js去除字符串中的空格
//去除空格 function Trime(string){ return string.replace(/\s/ig,""); }
- java中的中文字符转码技术
package com.yin.test; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; impor ...
- 9.DataGrid数据表格
后台获取数据并将其转换为json数组格式: 前台获取数据并显示在数据表格中:
- (使用STL自带的排序功能进行排序7.3.2)POJ 2092 Grandpa is Famous(结构体排序)
/* * POJ_2092.cpp * * Created on: 2013年11月1日 * Author: Administrator */ #include <iostream> #i ...
- 【xcode中添加pch全局引用文件】
前沿:xcode6中去掉了pch,为了一些琐碎的头文件引用,加快了 编译速度! xcode6之前的版本建项目就自动添加了是这样的: xcode6后的版本要自己手动的添加步骤如下: 1) 2) 3) ...
- 在mac下配置Andriod环境 包括eclipse和andriod studio
1 前提 已经配置好了java的环境,课上要使用andriod开发. 2 步骤 2.1 eclipse 2.1.1先安装adt,adt是一个在eclipse中开发andriod的插件.由于墙,我是从其 ...
- 关于.net core使用nginx做反向代理获取客户端ip的问题
1.正常情况下.net core获取客户端ip是比较简单的 /// <summary> /// 获取客户Ip /// </summary> /// <param name ...
- #loj3089 [BJOI2019]奥术神杖
卡精度好题 最关键的一步是几何平均数的\(ln\)等于所有数字取\(ln\)后的算术平均值 那么现在就变成了一个很裸的01分数规划问题,一个通用的思路就是二分答案 现在来考虑二分答案的底层怎么写 把所 ...
- 识别同音字词pypinyin, 分词 jieba
一.pypinyin 在处理语音输入指令时, 比如 请给圆圆发消息,那么转化为文字识别时, 无法确定转换的是圆圆还是园园或是源源, 为了解决这个问题, 就把指令转换为拼音来处理,这样就可以处理同音字了 ...