/// <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. SQL两表之间:根据一个表的字段更新另一个表的字段

    update table1 set field1=table2.field1,field2=table2.field2from table2where table1.id=table2.id

  2. 笔试中常用c++接口

    1.stack:https://www.cnblogs.com/hdk1993/p/5809161.html 使用该容器时需要包含#include<stack>头文件: 定义stack对象 ...

  3. jmeter断言接口响应字段大小

    一,有时候断言需要判断接口返回某个字段值是否大于或者小于预期值,此时断言需要用到BeanShell断言 写法如下: import com.alibaba.fastjson.JSONObject; // ...

  4. 《图解HTTP》读书笔记(七:通信数据转发程序-代理/网关/隧道)

    HTTP通信时,除客户端和服务器以外,还有一些用于通信数据转发的应用程序,例如代理.网关和隧道,它们可以配合服务器工作.这些服务器和应用程序可以将请求转发给通信线路上的下一站服务器,并且能接收从那台服 ...

  5. Nginx与PHP-FPM运行原理详解

    目录 1. 代理与反向代理 1. 正向代理:访问google.com 2. 反向代理:通过反向代理实现负载均衡 2. 初识Nginx与PHP-FPM 1. Nginx是什么 2. CGI与FastCG ...

  6. charles-Andriod 手机手机抓包乱码

    然后重启进行进行抓包

  7. python点点滴滴

    python点点滴滴 1 self 使用python编程实现邮箱登录时,遇到使用self的情况,在此做简要记录. 参考链接: https://sjolzy.cn/Why-should-self-Pyt ...

  8. 2019CCF-GAIR全球人工智能与机器人峰会于7月在深圳召开

    全球人工智能与机器人峰会(CCF-GAIR)是由中国计算机学会(CCF)主办,雷锋网.香港中文大学(深圳)承办,得到了深圳市政府的大力指导,是国内人工智能和机器人学术界.工业界及投资界三大领域的顶级交 ...

  9. 打开eclipse "Initializing Java Tooling"错误

    问题:打开eclipse初始化界面过程中弹出An internal error occurred during: "Initializing Java Tooling". java ...

  10. [virtualbox] win10与centos共享目录下,nginx访问问题

    原文,http://blog.csdn.net/zhezhebie/article/details/73554872 virtualbox自动挂载之后,默认是挂载在/media/sf_WWW下面的: ...