/// <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请求的更多相关文章

  1. PHP模拟发送POST请求之五curl基本使用和多线程优化

    今天来介绍PHP模拟发送POST请求的重型武器——cURL函数库的使用和其多线程的优化方法. 说起cURL函数,可谓是老生常谈,但网上许多资料都在关键部分语焉不详,列出一大堆手册上的东西,搞得我入门时 ...

  2. PHP模拟发送POST请求之一、HTTP协议头部解析

    WEB开发中信息基本全是在POST与GET请求与响应中进行,GET因其基于URL的直观,易被我们了解,可POST请求因其信息的隐蔽,在安全的同时,也给开发者们模拟发送带来了麻烦.接下来的几篇博文中,我 ...

  3. Loadrunner模拟JSON接口请求进行测试

    Loadrunner模拟JSON接口请求进行测试     一.loadrunner脚本创建 1.Insert - New step -选择Custom Request -  web_custom_re ...

  4. WebClient模拟发送Post请求

    WebClient模拟发送Post请求方法: /// <summary> /// 模拟post请求 /// </summary> /// <param name=&quo ...

  5. httpClient模拟浏览器发请求

    一.介绍 httpClient是Apache公司的一个子项目, 用来提高高效的.最新的.功能丰富的支持http协议的客户端编程工具包.完成可以模拟浏览器发起请求行为. 二.简单使用例子 : 模拟浏览器 ...

  6. 【转载】curl 模拟 GET\POST 请求,curl查看响应头 以及 curl post 上传文件

    补充说明:curl查看响应头 curl -I "http://www.baidu.com"HTTP/1.1 200 OK #HTTP协议 HTTP 返回码Server: Tengi ...

  7. CountDownLatch和CyclicBarrier模拟同时并发请求

    有时候要测试一下某个功能的并发能力,又不要想借助于其他测试工具,索性就自己写简单的demo模拟一个并发请求就最方便了.如果熟悉jemter的测试某接口的并发能力其实更专业,此处只是自己折腾着玩. Co ...

  8. php使用curl模拟多线程发送请求

    每个PHP文件的执行是单线程的,但是php本身也可以用一些别的技术实现多线程并发比如用php-fpm进程,这里用curl模拟多线程发送请求.php的curl多线程是通过不断调用curl_multi_e ...

  9. linux 模拟发http请求的例子

    curl -X POST --header "Content-Type: application/json" --header "Accept: */*" &q ...

  10. nodejs模拟http发送请求

    首先需要安装模块request,然后代码如下: //模拟发送http请求 var request = require("request"); //get请求 request('ht ...

随机推荐

  1. Django ORM存储datetime 时间误差8小时问题

    今天使用django ORM 将获取到的时间入库,并未出现问题,但是后来发现时间晚了8小时,经查询Django官方文档发现获取本地时间和UTC时间有差别. 首先科普下:UTC是协调世界时 UTC相当于 ...

  2. jmeter 之 if controller

    jmeter版本5.0.下面是jmeter5.0的if逻辑控制器的截图 标红字体的意思大概是,如果勾选了 下面的 interpret condition as variable expression ...

  3. 洛谷P4778 Counting swaps 数论

    正解:数论 解题报告: 传送门! 首先考虑最终的状态是固定的,所以可以知道初始状态的每个数要去哪个地方,就可以考虑给每个数$a$连一条边,指向一个数$b$,表示$a$最后要移至$b$所在的位置 显然每 ...

  4. pandas(二)

    层级索引: index=[('a',2010),('b',2011),('c',2010'),('a',2012),('e',2010),('f',2011)] age=[18,17,18,16,18 ...

  5. Asp.net Web Api开发(第四篇)Help Page配置和扩展

    https://blog.csdn.net/sqqyq/article/details/52708613

  6. IR2104s半桥驱动使用经验

    多次使用IR2104s,每次的调试都有种让人吐血的冲动.现在将使用过程遇到的错误给大家分享一下,方便大家找到思路. 一.自举电容部分(关键) 1.听说自举电路必须要安装场效应管,于是我在使用过程中,安 ...

  7. 文件中间修改内容遇到OSEerror

    for i in f: 实际上是一直在调用 f.next() .(表明在交互模式下不能使用f.tell())从报错来看,是说 f.next() 方法被调用的时候,f.tell() 方法不可以被调用.

  8. C++---使用VS在C++编程中出现 fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h"”?

    啦啦啦,好久没写博客啦... 对于C++初学者来说适应一个新的编译器还是需要蛮长一段时间的,现在我就给你们说说标题所说的这个问题吧... 第一步:菜单--〉项目--〉设置,出现“项目设置”对话框,左边 ...

  9. web攻击之xss(一)

    1,xss简介 跨站脚本攻击(Cross Site Scripting),为了不和层叠样式表(Cascading Style Sheets, CSS)的缩写混淆,故将跨站脚本攻击缩写为XSS.恶意攻击 ...

  10. 线段树 HDU-1754 I Hate It

    附上原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1754 Problem Description 很多学校流行一种比较的习惯.老师们很喜欢询问,从某某 ...