模拟浏览器请求(WebRequest)
运用场景: 现在假设有两个公司A 和 B,现在A公司想要访问B公司的的数据,而B公司我们不能直接的就把数据库暴露给A公司,于是B公司给A公司提供的一个请求url,通过这个请求就可以访问到B公司提供给A公司的请求,但是现在问题来了,A公司怎样通过B公司提供的url去获取想要的数据呢?于是乎,今天就学习了一下WebRequest这个类,以下是笔记。
1、这个是提供数据的解决方案中的代码,相当于B公司提供的接口(WebAPI)【B解决方案】
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; // 其他公司传递过来的参数 string blockType = context.Request.Params["BlockType"]; ///string blockNo = context.Request.Params["BlockNo"]; if (!string.IsNullOrEmpty(blockType) && blockType.Equals("SZ",StringComparison.OrdinalIgnoreCase)) { List<Block> blockList = new List<Block>() { new Block(){BlockNo=000001,BlockName="SHENHONG"}, new Block(){BlockNo=000002,BlockName="SHENHONG2"}, new Block(){BlockNo=000003,BlockName="SHENHONG3"} }; // blockList.Where(c=>c.BlockNo == Convert.ToInt32(blockNo)); JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(blockList); context.Response.Write(json); } }
2、以下是需要通过提供的url(接口)模拟浏览器请求的代码,相当于A公司【A解决方案】
protected void submit_Click(object sender, EventArgs e) { // 模拟请求http://localhost:3536/GetBlockData.ashx?blockType=SZ string requestUrl = "http://localhost:3536/GetBlockData.ashx?blockType=SZ&blockNo="+tbBlockNo.Text.Trim(); // 1.0 创建 WebRequest 请求对象。 WebRequest request = WebRequest.Create(requestUrl); // 1.1 设置请求的方法 request.Method = "Get"; // 1.2 发送请求并接收请求返回来的响应 WebResponse responseBody = request.GetResponse(); Stream stream = responseBody.GetResponseStream(); //1.3 把流读取为字符串 string responseContent = string.Empty; using (StreamReader sr = new StreamReader(stream)) { responseContent = sr.ReadToEnd(); } Response.Write(responseContent); }
总结:在web运用的时候,我们总有可能会遇到像以上情况那样,需要和其他公司合作的情况,这就需要提供数据的公司写WebAPI(接口),而需要数据的公司写的关键点就是 模拟浏览器发出请求,而目前接触的代码中可以通过WebReqeust类以及其相关的方法实现数据的获取。
扩展: 像网络爬虫估计是这么做的,不过爬取的网站返回的数据格式不一样,所以有不同的处理方式,如XML,HTML,JSON.(关于爬虫,后期去尝试)
2015-03-05
(2015年12月15日)
补充说明:今日在请求基于 HTTPS 的 webapi 时报错,错误提示是: 未能为 SSL/TLS 安全通道建立信任的解决办法 , 解决方案如下
1 public class WebReqeustHelper 2 { 3 public static string GetResponseContent(string RequestUrl) 4 { 5 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 6 string url = RequestUrl; 7 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 8 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 9 string encoding = response.ContentEncoding; 10 if (encoding == null || encoding.Length < 1) 11 { 12 encoding = "UTF-8"; //默认编码 13 } 14 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); 15 string content = reader.ReadToEnd(); 16 response.Close(); 17 return content; 18 } 19 20 public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 21 { 22 return true; //总是接受 23 } 24 25 }
2. 对webAPI的另外一种请求方式,添加引用 RestSharp.dll ,学习源 http://restsharp.org/
public string API { set { if (value != null) { api = value; } } get { return api; } } #region 0.1 api调用 #region 1.1 Post调用 参数为model /// <summary> /// Post调用 参数为model /// </summary> /// <param name="url">请求的url</param> /// <param name="requestbody">参数</param> /// <param name="contentType">Content-Type</param> /// <param name="charset">编码</param> /// <returns>dynamic{Status=200,Content=""}</returns> public dynamic PostApi(string url, object requestbody, string contentType = "application/json", string charset = "utf-8") { dynamic data = new ExpandoObject(); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string jsonExtend = javaScriptSerializer.Serialize(requestbody); var client = new RestClient(api + url); var request = new RestRequest(Method.POST); if (requestbody != null) { request.AddParameter("application/json; charset=utf-8", jsonExtend, ParameterType.RequestBody); } try { IRestResponse response = client.Execute(request); data.Status = HttpStatusCode.OK; data.Content = response.Content; } catch (Exception ex) { data.Status = HttpStatusCode.BadRequest; data.Content = ex.Message; } return data; } #endregion #region 1.2 Get|Post url+参数调用 /// <summary> /// Get|Post url+参数调用 /// </summary> /// <param name="url">请求的url</param> /// <param name="method">请求方式</param> /// <returns>dynamic{Status=200,Content=""}</returns> public dynamic Get_Post_Api(string url, Method method = Method.GET) { dynamic data = new ExpandoObject(); var client = new RestClient(api + url); var request = new RestRequest(method); try { IRestResponse response = client.Execute(request); data.Status = HttpStatusCode.OK; data.Content = response.Content; } catch (Exception ex) { data.Status = HttpStatusCode.BadRequest; data.Content = ex.Message; } return data; } #endregion