说明:
用泛型减少重复代码,使代码更合理、更优雅的API接口
主文:
有这样一个场景,需要对接接口,以获取取得数据。
例如获取订单列表
接口请求参数(json格式):
[C#] 纯文本查看 复制代码 {
//公共头部
"head":{
"method":"getOrders", //接口方法
"sign":"xxxx" //签名
},
//私有主体
"body":{
"userId":"1", //用户ID
"numPerPage":10, //页大小
"pageIdx":1 //页码
}
} 接口响应结果(json格式):
[C#] 纯文本查看 复制代码 {
"head":{
"code":1, //状态码
"errMsg":"成功" //消息
},
"body":{
"pageCount":value,
"pageIdx":value,
"orders":[
{
"orderNo":value,
"orderPrice":value,
"orderTime":value,
}
]
"status":value,
"orderStatus":value
省略...
}
}
通过观察请求参数和响应结果,会发现有部分字段是公共的,并且与接口交互的方法,大部分都是相同的,这里也可以提取封装,将不稳定容易出错的代码集中到一个地方;而如果对每个接口方法都进行一遍对接,重复的代码会不少,也很容易出错(对copy代码,吃过相当多的亏),所以对重复代码进行适当的封装,减少不必要的冗余,让代码结构更简单明了。
首先是提取公共的请求实体容器BaseWhere<T>:
[C#] 纯文本查看 复制代码 /// <summary>
/// 公共头部
/// <para>
/// 用于与接口通讯,发送请求数据的容器
/// 数据访问层使用
/// </para>
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseWhere<T> where T : new()
{
private headBaseWhere _head = new headBaseWhere();
/// <summary>
/// 公共头部
/// </summary>
public headBaseWhere head { get; set; }
private T _body = new T();
/// <summary>
/// 私有主体
/// </summary>
public T body { get; set; }
}
public class headBaseWhere
{
/// <summary>
/// 接口方法
/// </summary>
public String method { get; set; }
/// <summary>
/// 签名
/// </summary>
public String sign { get; set; }
}
接下来是提取公共的响应实体容器BaseResult<T>:
[C#] 纯文本查看 复制代码 /// <summary>
/// 返回报文报文头参数
/// <para>
/// 用于与接口通讯,接收返回数据的容器
/// 数据访问层使用
/// </para>
/// </summary>
/// <typeparam name="T"></typeparam>
public class BaseResult<T> where T : new()
{
private headBaseResult _head = new headBaseResult();
/// <summary>
/// 公共头部
/// </summary>
public headBaseResult head { get; set; }
private T _body = new T();
/// <summary>
/// 私有主体
/// </summary>
public T body { get; set; }
}
public class headBaseResult
{
/// <summary>
/// 状态码
/// </summary>
public String code { get; set; }
/// <summary>
/// 消息
/// </summary>
public String msg { get; set; }
}
然后定义订单列表的请求实体OrdersPara和响应实体OrdersResult:
[C#] 纯文本查看 复制代码 /// <summary>
/// 订单列表(请求实体)
/// </summary>
public class OrdersPara
{
public string userId { get; set; }
public int numPerPage { get; set; }
public int pageIdx { get; set; }
}
/// <summary>
/// 订单列表(响应实体)
/// </summary>
public class OrdersResult
{
private IList<Order> _orders = new List<Order>();
public int pageCount { get; set; }
public int pageIdx { get; set; }
public IList<Order> orders { get { return _orders; } set { _orders = value; } }
}
public class Order
{
private IList<OrderDetail> _detail = new List<OrderDetail>();
public string orderNo { get; set; }
public decimal orderPrice { get; set; }
public string orderTime { get; set; }
public int status { get; set; }
public int orderStatus { get; set; }
public int activityID { get; set; }
public string mobileNo { get; set; }
}
公共的请求方法WebAPIHelper<T>.POST(obj):
[C#] 纯文本查看 复制代码 public static class WebAPIHelper<T> where T : new()
{
public static BaseResult<T> Post(Object postData)
{
StringBuilder strResult = new StringBuilder();
//创建HttpWebRequest请求
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Settings.APIURL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//根据接口的要求序列化请求参数
String strParams = JsonConvert.SerializeObject(postData);
UTF8Encoding encoding = new UTF8Encoding();
request.ContentLength = encoding.GetByteCount(strParams);
request.Credentials = CredentialCache.DefaultCredentials;
try
{
//创建字节流
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(encoding.GetBytes(strParams), 0, encoding.GetByteCount(strParams));
}
//获取回传信息
using (WebResponse response = request.GetResponse())
{
Stream streamResult = response.GetResponseStream();
using (StreamReader reader = new StreamReader(streamResult))
{
strResult.Append(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
}
BaseResult<T> result = new BaseResult<T>();
try
{
result = JsonConvert.DeserializeObject<BaseResult<T>>(strResult.ToString());
}
catch (Exception ex)
{
}
if (result == null)
{
result = new BaseResult<T>();
}
if(result.body == null)
{
result.body = new T();
}
return result;
}
}
调用示例:
[C#] 纯文本查看 复制代码 public QueryOrdersResult Get(QueryOrdersPara para)
{
BaseWhere<OrdersPara> where = new BaseWhere<OrdersPara>();
where.head.method = "qryOrders";
where.body.userId = para.userId;
where.body.pageIdx = para.pageIdx;
where.body.numPerPage = para.numPerPage;
BaseResult<OrdersResult> result = WebAPIHelper<OrdersResult>.Post(where);
return result.body;
}
本贴转自博客园:http://www.cnblogs.com/chen-yu/archive/2015/07/27/4680651.html
|