模拟浏览器请求(WebRequest)

摘要:
//参数stringblockType=context。要求从其他公司传递的参数[“BlockType”]///stringblockNo=context.Request.Params[“BlockNo”];//blockList.其中(c=>blockType=SZ&

原文地址:https://www.cnblogs.com/mafei2014/articles/4316375.html

 运用场景: 现在假设有两个公司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

RestSharp 封装

免责声明:文章转载自《模拟浏览器请求(WebRequest)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇天气插件(vue)和风天气插件springsession生成sessionid不一致问题解决下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

location.href和location.replace和location.reload的不同(location.replace不记录历史)

location.href iframe.location.href window.location.href      整个URL字符串(在浏览器中就是完整的地址栏) reload 方法,该方法强迫浏览器刷新当前页面。     语法: location.reload([bForceGet])                               ...

CSS实用的代码段

摘抄的一些代码还有自己总结的常用的代码~ 1>浏览器样式统一 1 *{ 2 margin:0px; 3 padding:0px; 4 } 浏览器样式统一 2>清除浮动的方法 3>跨浏览器设置透明度 1 .transparent{ 2 filter:alpha(opacity=50); /*IE*/ 3 -khtml...

Python接口自动化-接口基础(二)

一、HTTP请求方式 1.常见请求方式 方法 描述 GET 请求指定的页面信息,并返回实体主体 HEAD 类似于 GET 请求,只不过返回的响应中没有具体的内容,用于获取报头 POST 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST 请求可能会导致新的资源的建立和/或已有资源的修改 PUT 从...

VIP视频解析接口,送给有需要的人

VIP视频解析接口:http://api.bbbbbb.me/jx/?url=http://www.a305.org/weixin.php?url=http://api.91exp.com/svip/?url=http://api.bbbbbb.me/ipsign/player.php?v=http://api.ledboke.com/vip/?url=h...

JS获取url参数

Location 对象包含有关当前 URL 的信息。 Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。 hash 设置或返回从井号 (#) 开始的 URL(锚)。host 设置或返回主机名和当前 URL 的端口号。hostname 设置或返回当前 URL 的主机名。href 设置或返回完整的 UR...

通过jQuery和C#分别实现对.NET Core Web Api的访问以及文件上传

建立.NET Core Web Api项目建立请求模型 public class UserInfo { public int Age { get; set; } public string Name { get; set; } public bool Sex { get; set; }...