转发http请求的实例
Posted tkevin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了转发http请求的实例相关的知识,希望对你有一定的参考价值。
在开发鹰眼轨迹控制台时,发现ak,sk都是暴露状态。这样非常不安全!
摘自提醒:管理台DEMO默认获取service_id和AK的方式是通过解析URL,为了您的数据安全,强烈将他们隐藏在后端。
这里主要是要把ak和service_id参数在转发请求时再加入到参数中,去请求真实路径,然后把请求结构返回前台。
客户端 -> 服务A -> 服务B ,然后再原路返回。转发发生在服务A中。
如果区分不开转发和重定向。可以 点击这里理解 区别
此实例在开发鹰眼轨迹服务中运用,其他服务如需要请忽略callback 的影响。既
if (result.IndexOf("(") > -1)
{
result = result.Substring(result.IndexOf("(") + 1, result.LastIndexOf(")") - result.IndexOf("(") - 1);//取消相应时的不必要数据(callback说明)
}
使用一般处理程序进行处理前台的请求,然后再转发到前台传入的参数url 去处理,请求方式同样由前台传入的参数agency_metbod
ah: 说明http: 还是 https: 如果传入的url 已经带上,则请删除
eagleEyeHandler .ashx
/// <summary> /// eagleEyeHandler 的摘要说明 /// </summary> public class eagleEyeHandler : IHttpHandler { /// <summary> /// 处理开始 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { string ak = "";//ak string service_id = "";//service_id var ah = "http:"; //转发地址 var url = context.Request["url"]; var agency_metbod = context.Request["agency_metbod"]; var callback = context.Request["callback"]; var metbod = context.Request.HttpMethod.ToUpper(); if (metbod != "GET" && metbod != "POST") { return;/* 非合法请求 停止处理业务 */ } //参数装载 Dictionary<string, string> id = new Dictionary<string, string>(); if (url == null) return;/*没有传输请求路径 停止处理业务*/ if (agency_metbod == null) agency_metbod = "GET"; //接到请求数据 代理转发 一律接收跨域请求 ajax jsonp (只能get传参) var sParams = string.Format("?ak={0}&service_id={1}&", ak, service_id); var QueryString = context.Request.QueryString; foreach (string item in QueryString.Keys) { /* callback说明 待定 是否要屏蔽callback参数 问题:如果相同的callback 并发足够快 服务器应该会返回 [callback] && [callback] ( jsonData ) */ if (item == "url" || item == "metbod") { continue; }//屏蔽不需要的参数 减少传输量 //|| item == "callback" sParams += string.Format("{0}={1}&", item, context.Request[item].ToString()); } HttpWebResponse hr = null; if (agency_metbod == "GET") hr = HttpWebResponseUtility.CreateGetHttpResponse(ah + url + sParams, null, null, null);//GET else hr = HttpWebResponseUtility.CreatePostHttpResponse(ah + url, sParams, null, null, System.Text.Encoding.UTF8, null);//POST StreamReader sr = new StreamReader(hr.GetResponseStream()); var result = sr.ReadToEnd();//读取所有数据 if (result.IndexOf("(") > -1) { result = result.Substring(result.IndexOf("(") + 1, result.LastIndexOf(")") - result.IndexOf("(") - 1);//取消相应时的不必要数据(callback说明) } sr.Close(); if (callback == null) context.Response.Write(result); else context.Response.Write(callback.ToString() + "(" + result + ")"); //LogWrite.AddUpdateLog("LOG", "http:" + url + sParams);//写入日志 //LogWrite.AddUpdateLog("LOG", callback.ToString() + "(" + result + ")"); context.Response.End(); } public bool IsReusable { get { return false; } } }
HttpWebResponseUtility.cs
/// /// 有关HTTP请求的辅助类 /// public class HttpWebResponseUtility { private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; /// /// 创建GET方式的HTTP请求 /// /// public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.UserAgent = DefaultUserAgent; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return request.GetResponse() as HttpWebResponse; } /// <summary> /// CreatePostHttpResponse 创建post请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="parameters">请求参数</param> /// <param name="timeout">过期时间 可为空</param> /// <param name="userAgent">userAgent 可为空</param> /// <param name="requestEncoding">编码格式</param> /// <param name="cookies">cookies</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); } i++; } byte[] data = requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } /// <summary> /// CreatePostHttpResponse 创建post请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="sParameters">请求参数 (?key=value&key1=value1...)</param> /// <param name="timeout">过期时间 可为空</param> /// <param name="userAgent">userAgent 可为空</param> /// <param name="requestEncoding">编码格式</param> /// <param name="cookies">cookies</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponse(string url, string sParameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } if (requestEncoding == null) { throw new ArgumentNullException("requestEncoding"); } HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } else { request.UserAgent = DefaultUserAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需要POST数据 if (sParameters != null && sParameters != "") { StringBuilder buffer = new StringBuilder(); buffer = buffer.Append(sParameters); byte[] data = requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return request.GetResponse() as HttpWebResponse; } private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //总是接受 } }
以上是关于转发http请求的实例的主要内容,如果未能解决你的问题,请参考以下文章