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;
}
}
C# 模拟 HTTP POST请求的更多相关文章
- PHP模拟发送POST请求之五curl基本使用和多线程优化
今天来介绍PHP模拟发送POST请求的重型武器——cURL函数库的使用和其多线程的优化方法. 说起cURL函数,可谓是老生常谈,但网上许多资料都在关键部分语焉不详,列出一大堆手册上的东西,搞得我入门时 ...
- PHP模拟发送POST请求之一、HTTP协议头部解析
WEB开发中信息基本全是在POST与GET请求与响应中进行,GET因其基于URL的直观,易被我们了解,可POST请求因其信息的隐蔽,在安全的同时,也给开发者们模拟发送带来了麻烦.接下来的几篇博文中,我 ...
- Loadrunner模拟JSON接口请求进行测试
Loadrunner模拟JSON接口请求进行测试 一.loadrunner脚本创建 1.Insert - New step -选择Custom Request - web_custom_re ...
- WebClient模拟发送Post请求
WebClient模拟发送Post请求方法: /// <summary> /// 模拟post请求 /// </summary> /// <param name=&quo ...
- httpClient模拟浏览器发请求
一.介绍 httpClient是Apache公司的一个子项目, 用来提高高效的.最新的.功能丰富的支持http协议的客户端编程工具包.完成可以模拟浏览器发起请求行为. 二.简单使用例子 : 模拟浏览器 ...
- 【转载】curl 模拟 GET\POST 请求,curl查看响应头 以及 curl post 上传文件
补充说明:curl查看响应头 curl -I "http://www.baidu.com"HTTP/1.1 200 OK #HTTP协议 HTTP 返回码Server: Tengi ...
- CountDownLatch和CyclicBarrier模拟同时并发请求
有时候要测试一下某个功能的并发能力,又不要想借助于其他测试工具,索性就自己写简单的demo模拟一个并发请求就最方便了.如果熟悉jemter的测试某接口的并发能力其实更专业,此处只是自己折腾着玩. Co ...
- php使用curl模拟多线程发送请求
每个PHP文件的执行是单线程的,但是php本身也可以用一些别的技术实现多线程并发比如用php-fpm进程,这里用curl模拟多线程发送请求.php的curl多线程是通过不断调用curl_multi_e ...
- linux 模拟发http请求的例子
curl -X POST --header "Content-Type: application/json" --header "Accept: */*" &q ...
- nodejs模拟http发送请求
首先需要安装模块request,然后代码如下: //模拟发送http请求 var request = require("request"); //get请求 request('ht ...
随机推荐
- anaconda安装tensorflow报错 No module named 'tensorflow'解决方法(windows)
这个错误的原因可能是,anaconda安装的python版本为3.7,现在tensorflow仅支持python 3.6 改变python版本:首先在命令行创建一个名为python36的环境,指定 ...
- 关于映射路径@ReuqestMapping的总结
何谓映射路径呢? 映射路径,就是匹配请求路径和执行方法关系的路径 基于注解的映射路径可以忽略前后缀,如: @RequestMapping(value="/say.do") @Req ...
- MySQL数据库常用命令和概念 (1)
一.数据库的创建: 1.创建一个名称为mydb1的数据库 create database mydb1; 2.创建一个使用utf8字符集的mydb2数据库. create database mydb2 ...
- visual studio 中被遗忘的任务列表和书签
任务列表(Task List)是VS中被人遗忘的一个功能,用到跳转到不同的代码段非常不便.以后就不用每次前进和后退导航了. 使用“任务列表” 跟踪使用 TODO 和 HACK或自定义令牌等令牌的代码注 ...
- Ubuntu server LTS 16.04安装SSH以及连接问题
1.SSH安装 出现问题: 登录到Ubuntu服务器,执行以下命令: sudo apt-get install openssh-server 出现以下错误: 解决办法: 1)确保服务器能出外网,比如说 ...
- c# 调用浏览器打开网址并全屏
关键性参数 Google Chrome浏览器 Process process = Process.Start("chrome.exe", " --kiosk " ...
- myeclipse2017下载安装与破解详细教程
下载myeclipse2017百度云下载路径: 链接:https://pan.baidu.com/s/1wQYwO2zrUvbbUcjCB5B8IQ 密码:6igu myeclipse2017破解文件 ...
- c# ASP.NET Core2.2利用中间件支持跨域请求
1.public void Configure(IApplicationBuilder app, IHostingEnvironment env)方法里面 不要加上:app.UseCors(); 2. ...
- Git命令(Git版本:Linux 2.14.3)
常用 git status 跟踪状态git commit -m "xxx" yyy.cppgit pull git pushgit mergetool --tool=meld 合并 ...
- 【JavaScript】第8章读书笔记
本章常用的DOM方法 切记,页面的逻辑是:创建新的元素,给新的元素创建内容,通过appendChild把新元素的内容插入到新元素节点中:通过appendChild把新元素插入到已有元素节点中 书上的老 ...