C# 模拟 HTTP POST请求
/// <summary>/// 用于以 POST 方式向目标地址提交表达数据/// 使用 application/x-www-form-urlencoded 编码方式/// 不支持上传文件, 若上传文件, 请使用<see cref="HttpPostFileRequestClient"/>/// </summary>public sealed class HttpPostRequestClient{#region - Private -private List<KeyValuePair<string, string>> _postDatas;#endregion/// <summary>/// 获取或设置数据字符编码, 默认使用<see cref="System.Text.Encoding.UTF8"/>/// </summary>public Encoding Encoding { get; set; } = Encoding.UTF8;/// <summary>/// 获取或设置 UserAgent/// </summary>public string UserAgent { get; set; } = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";/// <summary>/// 获取或设置 Accept/// </summary>public string Accept { get; set; } = "*/*";/// <summary>/// 获取或设置 Referer/// </summary>public string Referer { get; set; }/// <summary>/// 获取或设置 Cookie 容器/// </summary>public CookieContainer CookieContainer { get; set; } = new CookieContainer();/// <summary>/// 初始化一个用于以 POST 方式向目标地址提交不包含文件表单数据<see cref="HttpPostRequestClient"/>实例/// </summary>public HttpPostRequestClient(){this._postDatas = new List<KeyValuePair<string, string>>();}/// <summary>/// 设置表单数据字段, 用于存放文本类型数据/// </summary>/// <param name="fieldName">指定的字段名称</param>/// <param name="fieldValue">指定的字段值</param>public void SetField(string fieldName, string fieldValue){this._postDatas.Add(new KeyValuePair<string, string>(fieldName, fieldValue));}/// <summary>/// 以POST方式向目标地址提交表单数据/// </summary>/// <param name="url">目标地址, http(s)://sample.com</param>/// <returns>目标地址的响应</returns>public HttpWebResponse Post(string url){if (string.IsNullOrWhiteSpace(url))throw new ArgumentNullException(nameof(url));HttpWebRequest request = null;if (url.ToLowerInvariant().StartsWith("https")){request = WebRequest.Create(url) as HttpWebRequest;ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, c, ch, ss) => { return true; });request.ProtocolVersion = HttpVersion.Version11;ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;request.KeepAlive = true;ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100;ServicePointManager.Expect100Continue = false;}else{request = WebRequest.Create(url) as HttpWebRequest;}request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";request.UserAgent = this.UserAgent;request.Accept = this.Accept;request.Referer = this.Referer;request.CookieContainer = this.CookieContainer;var postData = string.Join("&", this._postDatas.Select(p => $"{p.Key}={p.Value}"));using(var requestStream = request.GetRequestStream()){var bytes = this.Encoding.GetBytes(postData);requestStream.Write(bytes, 0, bytes.Length);}return request.GetResponse() as HttpWebResponse;}/// <summary>/// 以POST方式向目标地址提交表单数据/// </summary>/// <param name="url">目标地址, http(s)://sample.com</param>/// <returns>目标地址的响应</returns>public async Task<HttpWebResponse> PostAsync(string url){if (string.IsNullOrWhiteSpace(url))throw new ArgumentNullException(nameof(url));HttpWebRequest request = null;if (url.ToLowerInvariant().StartsWith("https")){request = WebRequest.Create(url) as HttpWebRequest;ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, c, ch, ss) => { return true; });request.ProtocolVersion = HttpVersion.Version11;ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;request.KeepAlive = true;ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100;ServicePointManager.Expect100Continue = false;}else{request = WebRequest.Create(url) as HttpWebRequest;}request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded";request.UserAgent = this.UserAgent;request.Accept = this.Accept;request.Referer = this.Referer;request.CookieContainer = this.CookieContainer;var postData = string.Join("&", this._postDatas.Select(p => $"{p.Key}={p.Value}"));using (var requestStream = await request.GetRequestStreamAsync()){var bytes = this.Encoding.GetBytes(postData);requestStream.Write(bytes, 0, bytes.Length);}return await request.GetResponseAsync() as HttpWebResponse;}}
/// <summary>/// 用于以 POST 方式向目标地址提交表单数据, 仅适用于包含文件的请求/// </summary>public sealed class HttpPostFileRequestClient{#region - Private -private string _boundary;private List<byte[]> _postDatas;#endregion/// <summary>/// 获取或设置数据字符编码, 默认使用<see cref="System.Text.Encoding.UTF8"/>/// </summary>public Encoding Encoding { get; set; } = Encoding.UTF8;/// <summary>/// 获取或设置 UserAgent/// </summary>public string UserAgent { get; set; } = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";/// <summary>/// 获取或设置 Accept/// </summary>public string Accept { get; set; } = "*/*";/// <summary>/// 获取或设置 Referer/// </summary>public string Referer { get; set; }/// <summary>/// 获取或设置 Cookie 容器/// </summary>public CookieContainer CookieContainer { get; set; } = new CookieContainer();/// <summary>/// 初始化一个用于以 POST 方式向目标地址提交表单数据的<see cref="HttpPostFileRequestClient"/>实例/// </summary>public HttpPostFileRequestClient(){this._boundary = DateTime.Now.Ticks.ToString("X");this._postDatas = new List<byte[]>();}/// <summary>/// 设置表单数据字段, 用于存放文本类型数据/// </summary>/// <param name="fieldName">指定的字段名称</param>/// <param name="fieldValue">指定的字段值</param>public void SetField(string fieldName, string fieldValue){var field = $"--{this._boundary}\r\n" +$"Content-Disposition: form-data;name=\"{fieldName}\"\r\n\r\n" +$"{fieldValue}\r\n";this._postDatas.Add(this.Encoding.GetBytes(field));}/// <summary>/// 设置表单数据字段, 用于文件类型数据/// </summary>/// <param name="fieldName">字段名称</param>/// <param name="fileName">文件名</param>/// <param name="contentType">内容类型, 传入 null 将默认使用 application/octet-stream</param>/// <param name="fs">文件流</param>public void SetField(string fieldName, string fileName, string contentType, Stream fs){var fileBytes = new byte[fs.Length];using (fs){fs.Read(fileBytes, 0, fileBytes.Length);}SetField(fieldName, fileName, contentType, fileBytes);}/// <summary>/// 设置表单数据字段, 用于文件类型数据/// </summary>/// <param name="fieldName">字段名称</param>/// <param name="fileName">文件名</param>/// <param name="contentType">内容类型, 传入 null 将默认使用 application/octet-stream</param>/// <param name="fileBytes">文件字节数组</param>public void SetField(string fieldName, string fileName, string contentType, byte[] fileBytes){var field = $"--{this._boundary}\r\n" +$"Content-Disposition: form-data; name=\"{fieldName}\";filename=\"{fileName}\"\r\n" +$"Content-Type:{contentType ?? "application/octet-stream"}\r\n\r\n";this._postDatas.Add(this.Encoding.GetBytes(field));this._postDatas.Add(fileBytes);this._postDatas.Add(this.Encoding.GetBytes("\r\n"));}/// <summary>/// 以POST方式向目标地址提交表单数据/// </summary>/// <param name="url">目标地址, http(s)://sample.com</param>/// <returns>目标地址的响应</returns>public HttpWebResponse Post(string url){if (string.IsNullOrWhiteSpace(url))throw new ArgumentNullException(nameof(url));HttpWebRequest request = null;if (url.ToLowerInvariant().StartsWith("https")){request = WebRequest.Create(url) as HttpWebRequest;ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, c, ch, ss) => { return true; });request.ProtocolVersion = HttpVersion.Version11;ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;request.KeepAlive = true;ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100;ServicePointManager.Expect100Continue = false;}else{request = WebRequest.Create(url) as HttpWebRequest;}request.Method = "POST";request.ContentType = "multipart/form-data;boundary=" + _boundary;request.UserAgent = this.UserAgent;request.Accept = this.Accept;request.Referer = this.Referer;request.CookieContainer = this.CookieContainer;var end = $"--{this._boundary}--\r\n";this._postDatas.Add(this.Encoding.GetBytes(end));var requestStream = request.GetRequestStream();foreach (var item in this._postDatas){requestStream.Write(item, 0, item.Length);}return request.GetResponse() as HttpWebResponse;}/// <summary>/// 以POST方式向目标地址提交表单数据/// </summary>/// <param name="url">目标地址, http(s)://sample.com</param>/// <returns>目标地址的响应</returns>public async Task<HttpWebResponse> PostAsync(string url){if (string.IsNullOrWhiteSpace(url))throw new ArgumentNullException(nameof(url));HttpWebRequest request = null;if (url.ToLowerInvariant().StartsWith("https")){request = WebRequest.Create(url) as HttpWebRequest;ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((s, c, ch, ss) => { return true; });request.ProtocolVersion = HttpVersion.Version11;ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;request.KeepAlive = true;ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100;ServicePointManager.Expect100Continue = false;}else{request = WebRequest.Create(url) as HttpWebRequest;}request.Method = "POST";request.ContentType = "multipart/form-data;boundary=" + _boundary;request.UserAgent = this.UserAgent;request.Accept = this.Accept;request.Referer = this.Referer;request.CookieContainer = this.CookieContainer;var end = $"--{this._boundary}--\r\n";this._postDatas.Add(this.Encoding.GetBytes(end));var requestStream = await request.GetRequestStreamAsync();foreach (var item in this._postDatas){await requestStream.WriteAsync(item, 0, item.Length);}return await request.GetResponseAsync() as HttpWebResponse;}}
转载于:https://www.cnblogs.com/aning2015/p/10458866.html
C# 模拟 HTTP POST请求相关推荐
- Node.js模拟发起http请求从异步转同步的5种方法
使用Node.js模拟发起http请求很常用的,但是由于Node模块(原生和第三方库)提供里面的方法都是异步,对于很多场景下应用很麻烦,不如同步来的方便.下面总结了几个常见的库API从异步转同步的几种 ...
- python post请求 上传图片_利用python模拟实现POST请求提交图片的方法
本文主要给大家介绍的是关于利用python模拟实现POST请求提交图片的方法,分享出来供大家参考学习,下面来一看看详细的介绍: 使用requests来模拟HTTP请求本来是一件非常轻松的事情,比如上传 ...
- pythonrequests发送数据_在python中使用requests 模拟浏览器发送请求数据的方法
在python中使用requests 模拟浏览器发送请求数据的方法 如下所示: import requests url='http://####' proxy={'http':'http://#### ...
- telnet客户端模拟浏览器发送请求
telnet 客户端 telnet客户端能够发出请求去连接服务器(模拟浏览器) 使用telnet之前,需要开启telnet客户端 1.进入控制面板 2.进入程序和功能,选择打开或关闭windows功能 ...
- JAVA模拟HTTP post请求上传图片
2019独角兽企业重金招聘Python工程师标准>>> 1.原理:实现思路和具体步骤就是模拟页面的请求 /*** @author qimh* @description 模拟form表 ...
- dueros模拟测试没有请求后台_实战 | 用手写一个骚气的请求合并,演绎底层的真实...
来源:公众号[ java进阶架构师] 好文推荐: 字节跳动Java岗4面面经分享:索弓|+rabbitmq+spring+Redis 拼多多面经Java开发3面面经:准备好久没想到面试题超级简单 网易 ...
- loadrunner发送json_Loadrunner模拟JSON接口请求进行测试
Loadrunner模拟JSON接口请求进行测试 一.loadrunner脚本创建 1.Insert - New step -选择Custom Request - web_custom_request ...
- jmeter测试TCP服务器/模拟发送TCP请求
jmeter测试TCP服务器,使用TCP采样器模拟发送TCP请求. TCP采样器:打开一个到指定服务器的TCP / IP连接,然后发送指定文本并等待响应. jmeter模拟发送TCP请求的方法: 1. ...
- php多线程模拟请求,浅谈php使用curl模拟多线程发送请求
每个PHP文件的执行是单线程的,但是php本身也可以用一些别的技术实现多线程并发比如用php-fpm进程,这里用curl模拟多线程发送请求.php的curl多线程是通过不断调用curl_multi_e ...
- 使用谷歌浏览器模拟发送http请求
下载一个chromed的插件postman附上下载地址http://download.csdn.net/detail/zhenghui89/8490331;下载以后解压缩;打开谷歌浏览器以后 依次 ...
最新文章
- 陈鑫136201010502
- 表格存储 SQL 查询多元索引
- 一文读懂VictoriaMetrics集群方案
- 【华为云技术分享】LiteOS无法直接烧录或者烧录失败解决方法--ST-Link
- .Net魔法堂:史上最全的ActiveX开发教程——部署篇
- 力扣-386 字典序排数
- 计算机专业 美国,美国计算机专业的五大名校概况
- 文献格式 ShareLaTeX and Overleaf
- python字符串转为ascii码_Python学习经验:无重复字符的最长子串
- 简单读取带有EXCEL宏病毒文件的内容
- 计算机电脑如何快捷粘贴,电脑粘贴快捷键在哪里【详细介绍】
- FRM-18108 FRM-10102错误解决
- chia windows接入hpool矿池
- 如何查看Safari浏览器network里Request的Payload
- 批量关闭开启wordpress文章的评论功能
- Educational Codeforces Round 62 (Rated for Div. 2) E. Palindrome-less Arrays(DP+瞎搞)
- protected和包访问权限
- 计算机应用基础论文1000字,计算机应用基础论文.doc
- Intellij Idea Database schemas显示
- 用python画玫瑰花