前言
过程,如图:
第一步创建一个帮助类,类里面提供了加密、组装Url等方法,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text; namespace APIClient.Content
{
public class WebHelper
{ #region 获得客户端时间+ public static int GetTimeZ(DateTime time)
public static int GetTimeZ(DateTime time)
{
var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(, , ));
return (int)(time - startTime).TotalSeconds;
}
#endregion #region 加密key+private string CreateSign(Dictionary<string, string> paramList, string appKey)
public static string CreateSign(Dictionary<string, string> paramList, string appKey)
{
var str = paramList.OrderBy(c => c.Key).Aggregate(string.Empty, (current, item) => current + item.Value);
return MD5(str + appKey).ToLower();//调用MD5
}
#endregion #region 执行HTTP GET请求+ public static string DoGet(string url, IDictionary<string, string> parameters)
public static string DoGet(string url, IDictionary<string, string> parameters)
{
if (parameters != null && parameters.Count > )
{
if (url.Contains("?"))
{
url = url + "&" + BuildPostDate(parameters); //调用BuildPostDate
}
else
{
url = url + "?" + BuildPostDate(parameters);
}
} HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.KeepAlive = true;
req.UserAgent = "ADCSDK";
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding); //调用GetResponseAsString
} #endregion #region MD5加密+ public static string MD5(string input)
/// <summary>
/// MD5加密 (添加命名空间;using System.Security.Cryptography;)
/// </summary>
/// <param name="input">输入字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5(string input)
{
if (string.IsNullOrEmpty(input))
{
return string.Empty;
} var md5 = new MD5CryptoServiceProvider();
var inputBytes = Encoding.UTF8.GetBytes(input);
var outPutbytes = md5.ComputeHash(inputBytes);
return BitConverter.ToString(outPutbytes).Replace("-", "");
}
#endregion #region 组装普通文本请求参数+ private static string BuildPostDate(IDictionary<string, string> parameters)
private static string BuildPostDate(IDictionary<string, string> parameters)
{
StringBuilder postDate = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
{
if (hasParam)
{
postDate.Append("&");
}
postDate.Append(name);
postDate.Append("=");
postDate.Append(Uri.EscapeDataString(value));
hasParam = true;
}
}
return postDate.ToString();
}
#endregion #region 把响应流转换为文本+ private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
StringBuilder result = new StringBuilder();
Stream stream = null;
StreamReader reader = null; try
{
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
var buffer = new char[];
int readBytes;
while ((readBytes = reader.Read(buffer, , buffer.Length)) > )
{
result.Append(buffer, , readBytes);
}
}
finally
{
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
return result.ToString();
}
#endregion }
}
第二步服务器端创建一个API(参数协商定义),代码如下:
public ActionResult Reg(int productId, string version, string source, string userName, string timeZ, string sign)
{
if (string.IsNullOrEmpty(version))
return Content("productId");
if (string.IsNullOrEmpty(version))
return Content("version");
if (string.IsNullOrEmpty(version))
return Content("source");
if (string.IsNullOrEmpty(version))
return Content("userName");
if (string.IsNullOrEmpty(version))
return Content("timeZ");
if (string.IsNullOrEmpty(version))
return Content("sign1"); var dict = new Dictionary<string, string>
{
{"productId", productId.ToString()},
{"version", version},
{"source", source},
{"userName", userName},
{"timeZ", timeZ},
}; var checkSign =WebHelper.CreateSign(dict, "zz680000f7-6834");//sign 是数据库中一个key,这里是为了方便,应当是根据productId值从数据库中取出相应的key与程序传过来的key比较 if (sign.ToLower() != checkSign.ToLower())
{
return Content("sign2");
}
//调用接口之后还应当在数据库中插入一条日志数据
return Content("");
}
第三步应用程序创建一个方法,请求API,代码如下:
public ActionResult List()
{
RegTest();
return View();
}
//参数
private const string APIUrl = "http://localhost:4023/APISever/";
private const int ProductId = ;
private const string AppKey = "zz680000f7-68341";//680000f7-6834-4b5f-8534-70cea7fd641b //注册接口
public void RegTest()
{
var url = string.Format("{0}reg", APIUrl);
var dict = new Dictionary<string, string>
{
{"productId", ProductId.ToString()},
{"version", "1.0.0.1"},
{"source", "lg"},
{"userName", "zlzl"},
{"timeZ",WebHelper.GetTimeZ(DateTime.Now).ToString()},//调用GetTimeZ
}; dict["sign"] =WebHelper.CreateSign(dict, AppKey);//调用CreateSign var result = WebHelper.DoGet(url, dict);//调用DoGet
Response.Write(string.Format("注册接口测试结果:{0}",result));
}