通过HttpWebRequest请求与HttpWebResponse响应方式发布接口与访问接口

时间:2022-04-17 23:00:57

一、API接口的编码

1、首页的页面代码:

    protected void Page_Load(object sender, EventArgs e)
{
/*
* 请求路径:http://xxxx/index.aspx?appkey=&security=&t=&method=&...
* appkey是调用者身份码(系统分配)
* security是当前请求安全码(安全码=MD5(Key + Method),key为系统分配或调用者自行设定)
* t是请求模块(Member用户模块 Berth泊位模块 Transaction交易模块 Operation运维模块 Equipment设备模块 Other其他模块)
* method是请求函数
*/
Response.Expires = ;//页面使用后立即过期
Response.CacheControl = "no-cache";//设置页面不缓存在临时文件中.
DateTime dtStart = DateTime.Now;
if (!IsPostBack)
{
string strT = SZRPP.Common.SZRPPRequest.GetString("t");
//构造分类请求转发地址
string strHeadUrl = ConfigurationManager.AppSettings[strT];
string strQueryUrl = strT + "API/Index.aspx";
string strReturn = "";
string strParm = GetAllParameter();
StreamReader sr = null;
HttpWebResponse res = null;
if (strT != "" && strHeadUrl != "")
{
try
{
//请求转发
// HttpWebRequest 是 WebRequest 的派生类,专门用于 Http
HttpWebRequest req = HttpWebRequest.Create(strHeadUrl + strQueryUrl) as System.Net.HttpWebRequest;
//设置请求方式
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//写入流对象
StreamWriter requestWriter = new StreamWriter(req.GetRequestStream());
//写入请求参数
requestWriter.Write(strParm);
//释放写入流对象
requestWriter.Close();
requestWriter = null;
//GetResponse 方法才真的发送请求,等待服务器返回
res = req.GetResponse() as HttpWebResponse;
//以流的形式表示的回应内容
Stream str = res.GetResponseStream();
//将字节流包装为高级的字符流,以便于读取文本内容
sr = new StreamReader(str, System.Text.Encoding.UTF8);
//读取响应内容
strReturn = sr.ReadToEnd();
}
catch (Exception ex)
{
//记录异常日志
SZRPP.Common.Utils.WriteLogFile("请求重定向异常:" + ex.Message + " [" + strHeadUrl + strQueryUrl + "?" + strParm + "]", "异常日志");
}
finally
{
//关闭字符流,字符流底层的字节流将会自动关闭
if (sr != null)
sr.Close();
if (res != null)
res.Close();
}
}
Response.ClearContent();
//输出响应内容
Response.Write(Input.LostHTML(Input.URLDecode(strReturn)));
//TimeSpan tsTotal = DateTime.Now - dtStart;
//SZRPP.Common.Utils.WriteLogFile("请求内容:" + strParm + "\r\n响应内容:" + strReturn + "\r\n耗时:" + tsTotal.TotalSeconds + "秒 来源:" + SZRPPRequest.GetIP() + "\r\n\r\n", "-" + DateTime.Now.Hour + strT + "响应日志", "接口监控详情");
}
Response.End();
} /// <summary>
/// 获取所有参数重新拼接
/// </summary>
private string GetAllParameter()
{
StringBuilder sb = new StringBuilder();
foreach (string strKey in Request.Params.AllKeys)
{
if (SZRPPRequest.GetString(strKey) != "")
{
if (sb.Length > )
sb.Append("&");
sb.Append(strKey + "=" + SZRPPRequest.GetString(strKey));
}
}
return sb.ToString();
}

2、SZRPPRequest类方法(SZRPP.Common.SZRPPRequest.GetString("t"))

 /// <summary>
/// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
/// </summary>
/// <param name="strName">参数</param>
/// <returns>Url或表单参数的值</returns>
public static string GetString(string strName)
{
if ("".Equals(GetQueryString(strName)))
{
strName =GetFormString(strName);
return strName;
}
else
{
strName = GetQueryString(strName);
return strName; }
} /// <summary>
/// 获得指定Url参数的值
/// </summary>
/// <param name="strName">Url参数</param>
/// <returns>Url参数的值</returns>
public static string GetQueryString(string strName)
{
if (HttpContext.Current.Request.QueryString[strName] == null)
{
return "";
}
return HttpContext.Current.Request.QueryString[strName];
} /// <summary>
/// 获得指定Url参数的值
/// </summary>
/// <param name="strName">Url参数</param>
/// <returns>Url参数的值</returns>
public static string GetQueryString(string strName)
{
if (HttpContext.Current.Request.QueryString[strName] == null)
{
return "";
}
return HttpContext.Current.Request.QueryString[strName];
}

3、API目录及发布在IIS上后的访问格式:

通过HttpWebRequest请求与HttpWebResponse响应方式发布接口与访问接口

通过浏览器访问的格式:http://10.10.40.184:6066/Index.aspx?appkey=123456&security=4564646545455&t=Berth&method=getberth

其中【Berth】为【berthAPI】目录,【getberth】为【berthAPI】目录下index.aspx.cs下的【getberth】方法

4、API返回内容页面代码的编写(如【berthAPI】目录下的【index.aspx.cs】代码:

protected void Page_Load(object sender, EventArgs e)
{
APIHelper.CheckRequestSecurity();
Response.Expires = ;
Response.CacheControl = "no-cache";
Response.ClearContent();
if (!IsPostBack)
{
string strMethod = SZRPPRequest.GetString("method").ToString("filtersql").ToLower();
try
{
switch (strMethod)
{
//2.1 获取深圳市行政区列表
case "getcanton":
GetSZCanton();
break;
//2.2 获取某行政区下片区列表
case "getarea":
GetAreaByCa();
break;
//2.3 获取某片区下路段列表
case "getsection":
GetSectionByAr();
break;
//2.4 获取某路段下泊位列表
case "getberthbyse":
GetBerthBySE();
break;
//2.5 获取附近泊位列表(多少米以内)
case "getbearbyberth":
GetBearByBerth();
break;
//2.6 获取行政区下路段列表
case "getsectionbyca":
GetSectionByCA();
break;
//2.7 获取路段的收费规则
case "getchargingrules":
GetChargingRules();
break;
case "getberth":
GetBerthInfo();
break;
default:
break;
}
}
catch (System.Threading.ThreadAbortException) { }
catch (Exception ex)
{
//记录异常日志
SZRPP.Common.Utils.WriteLogFile("BerthAPI发生异常【" + ex.TargetSite.Name + "】:" + ex.Message + " " + ex.StackTrace, "异常日志");
}
}
Response.End();
} #region 获取深圳市行政区列表
/// <summary>
/// 获取深圳市行政区列表
/// </summary>
private void GetSZCanton()
{
StringBuilder sb = new StringBuilder();
CantonBll cantonBll = new CantonBll();
DataTable dt = null;
if (DataCache.GetCache("APICanton") == null)
{
dt = cantonBll.GetList();
DataCache.SetCache("APICanton", dt);
}
else
{
dt = (DataTable)DataCache.GetCache("APICanton");
}
if (dt != null && dt.Rows.Count > )
{
sb.Append("{\"count\":" + dt.Rows.Count + ",");
sb.Append("\"items\":");
sb.Append("[");
foreach (DataRow dr in dt.Rows)
{
sb.Append("{");
sb.Append("\"CantonId\":\"" + dr["CantonId"].ToString() + "\",");
sb.Append("\"CantonCode\":\"" + dr["CantonCode"].ToString() + "\",");
sb.Append("\"CantonName\":\"" + dr["CantonName"].ToString() + "\",");
sb.Append("\"CantonLat\":\"" + dr["CantonLat"].ToString() + "\",");
sb.Append("\"CantonLng\":\"" + dr["CantonLng"].ToString() + "\",");
sb.Append("\"BerthNums\":\"" + dr["BerthNums"].ToString() + "\"");
sb.Append("},");
}
sb.Remove(sb.Length - , );
sb.Append("]}");
APIHelper.ReturnData(APIHelper.ReturnStatus.成功, "success", "成功", sb.ToString());
}
else
{
APIHelper.ReturnData(APIHelper.ReturnStatus.失败, "no_data", "没有行政区", "");
}
}
#endregion #region 单泊位查询
/// <summary>
/// 单泊位信息查询
/// </summary>
private void GetBerthInfo()
{
//泊位编号
string strBerthCode = SZRPPRequest.GetString("berthcode").ToString("filtersql");
BerthBll berthBll = new BerthBll();
DataTable dtBerth = berthBll.GetBerthInfo(strBerthCode);
if (dtBerth != null && dtBerth.Rows.Count > )
{
DataRow dr = dtBerth.Rows[];
StringBuilder sb = new StringBuilder();
//泊位编号
sb.Append("{\"berthcode\":\"" + dr["BerthCode"].ToString() + "\"");
//片区
sb.Append(",\"areaid\":\"" + dr["AreaId"].ToString() + "\"");
//行政区
sb.Append(",\"cantonid\":\"" + dr["CantonId"].ToString() + "\"");
//泊位状态
sb.Append(",\"berthstatus\":\"" + dr["BerthStatus"].ToString() + "\"");
//经度
sb.Append(",\"berthlongitude\":\"" + dr["BerthLongitude"].ToString() + "\"");
//纬度
sb.Append(",\"berthlatitude\":\"" + dr["BerthLatitude"].ToString() + "\"");
//停车状态
sb.Append(",\"parkstatus\":\"" + dr["ParkStatus"].ToString() + "\"}"); APIHelper.ReturnData(APIHelper.ReturnStatus.成功, "success", "成功", sb.ToString());
}
else
APIHelper.ReturnData(APIHelper.ReturnStatus.失败, "berth_not_exist", "抱歉,您输入的泊位号不存在", ""); }
#endregion #region 获取所有的行政区和片区 private void GetCantonAndArea()
{
StringBuilder sb = new StringBuilder(); #region 获取行政区 DataTable dtCanton = null;
if (DataCache.GetCache("APICanton") == null)
{
CantonBll cantonBll = new CantonBll();
dtCanton = cantonBll.GetList();
DataCache.SetCache("APICanton", dtCanton);
}
else
{
dtCanton = (DataTable)DataCache.GetCache("APICanton");
} #endregion #region 获取片区 DataTable dtArea = null;
if (DataCache.GetCache("APIArea") == null)
{
AreaBll areaBll = new AreaBll();
dtArea = areaBll.GetAreaList();
DataCache.SetCache("APIArea", dtArea);
}
else
{
dtArea = (DataTable)DataCache.GetCache("APIArea");
} #endregion if (dtCanton != null && dtCanton.Rows.Count > )
{
if (dtArea != null && dtArea.Rows.Count > )
{
sb.Append("{\"cantons\":");
sb.Append("[");
foreach (DataRow dr in dtCanton.Rows)
{
sb.Append("{");
sb.Append("\"CantonId\":\"" + dr["CantonId"].ToString() + "\",");
sb.Append("\"CantonName\":\"" + dr["CantonName"].ToString() + "\"");
sb.Append("},");
}
sb.Remove(sb.Length - , );
sb.Append("],"); sb.Append("\"areas\":");
sb.Append("[");
foreach (DataRow dr in dtArea.Rows)
{
sb.Append("{");
sb.Append("\"AreaId\":\"" + dr["AreaId"].ToString() + "\",");
sb.Append("\"CantonId\":\"" + dr["CantonId"].ToString() + "\",");
sb.Append("\"AreaName\":\"" + dr["AreaName"].ToString() + "\"");
sb.Append("},");
}
sb.Remove(sb.Length - , );
sb.Append("]}"); APIHelper.ReturnData(APIHelper.ReturnStatus.成功, "success", "成功", sb.ToString());
}
else
{
APIHelper.ReturnData(APIHelper.ReturnStatus.失败, "no_Area", "没有片区数据", "");
}
}
else
{
APIHelper.ReturnData(APIHelper.ReturnStatus.失败, "no_Canton", "没有行政区数据", "");
}
} #endregion

二、接口的请求

     private readonly string url = ConfigurationManager.AppSettings["API"];
        private readonly string versontype = ConfigurationManager.AppSettings["versontype"];
        private readonly string appkey = ConfigurationManager.AppSettings["appkey"];
        private readonly string security = ConfigurationManager.AppSettings["security"];      public ActionResult Login()
{
string login = SZRTCRequest.GetString("login").ToString("filtersql");
string up = SZRTCRequest.GetString("up").ToString("filtersql");
string lastUrl = SZRTCRequest.GetString("u");
string safeCode = SZRTCRequest.GetString("safeCode").ToString("filtersql"); Session["Login"] = null;
ViewBag.LastUrl = lastUrl.ToString();//记录session失效前最后一次访问路径
if (!Request.IsAjaxRequest())
{
return View();
}
Dictionary<string, object> dic=null;
string strJson = "";
try
{
StringBuilder sb = new StringBuilder();
sb.Append(url);
sb.Append("MemberAPI/Index.aspx?versontype=" + versontype);
sb.Append("&appkey="+appkey);
sb.Append("&security=" + oldsecurity);
sb.Append("&t=Member&method=login&mobileno=" + login + "&pwd=" + MD5_SHA.EncryptPassword(up));
sb.Append("&sign="+sign); strJson = CommonLogic.GetJsonStr(sb.ToString()); var jss = new JavaScriptSerializer();
dic = (Dictionary<string, object>)jss.DeserializeObject(strJson);
}
catch (Exception ex)
{
Utils.WriteLogFile("调用Login方法时报错,错误信息:" + ex.Message, "登录异常");
} if (dic != null)
{
int status = int.Parse(dic["status"].ToString());
string msg = dic["msg"].ToString();
if (status == )
{
object data = dic["data"];
Session["Login"] = data;
} return Content(strJson);
}
else
{
return Content("-1"); }
} /// <summary>
/// 根据路径返回json字符
/// </summary>
/// <param name="url">调用接口路径</param>
/// <returns>返回json字符</returns>
public static string GetJsonStr(string url)
{
string message = "";
string strJson = "";
try
{
HttpWebRequest req = null;
HttpWebResponse webResp = null;
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST"; // Post method
req.ContentType = "text/html"; // content type
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(message);
writer.Close();
webResp = (HttpWebResponse)req.GetResponse();
Stream answer = webResp.GetResponseStream();
StreamReader answerData = new StreamReader(answer, Encoding.UTF8);
strJson = answerData.ReadToEnd(); }
catch (Exception ex)
{
Utils.WriteLogFile("接口调用出现异常,异常信息:"+ex.Message,"接口调用异常");
}
return strJson;
}