ASP.NET HTTP模拟提交通用类 GET POST
用法:
WebRequestSugar ws = new WebRequestSugar();
//可选参数
//ws.SetAccept
//ws.SetContentType
//ws.SetCookie
//ws.SetTimeOut
//ws.SetIsAllowAutoRedirect //GET
var html= ws.HttpGet("http://localhost:24587/Http/HttpTest.aspx"); //带参GET
var paras=new Dictionary<string, string>() ;
paras.Add("name","skx");
paras.Add("id", "100");
var html2 = ws.HttpGet("http://localhost:24587/Http/HttpTest.aspx",paras ); //POST
var postHtml= ws.HttpPost("http://localhost:24587/Http/HttpTest.aspx", paras); //post and file
var postHtml2 = ws.HttpUploadFile("http://localhost:24587/Http/HttpTest.aspx", "文件地址可以是数组", paras);
类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Collections.Specialized; namespace SyntacticSugar
{ /// <summary>
/// ** 描述:模拟HTTP POST GET请求并获取数据
/// ** 创始时间:2015-11-24
/// ** 修改时间:-
/// ** 作者:sunkaixuan
/// ** 使用说明:
/// </summary>
public class WebRequestSugar
{
/// <summary>
/// 设置cookie
/// </summary>
private CookieContainer cookie; /// <summary>
/// 是否允许重定向
/// </summary>
private bool allowAutoRedirect = true; /// <summary>
/// contentType
/// </summary>
private string contentType = "application/x-www-form-urlencoded"; /// <summary>
/// accept
/// </summary>
private string accept = "*/*"; /// <summary>
/// 过期时间
/// </summary>
private int time = 5000; /// <summary>
/// 设置请求过期时间(单位:毫秒)(默认:5000)
/// </summary>
/// <param name="time"></param>
public void SetTimeOut(int time)
{
this.time = time;
} /// <summary>
/// 设置accept(默认:*/*)
/// </summary>
/// <param name="accept"></param>
public void SetAccept(string accept)
{
this.accept = accept;
} /// <summary>
/// 设置contentType(默认:application/x-www-form-urlencoded)
/// </summary>
/// <param name="contentType"></param>
public void SetContentType(string contentType)
{
this.contentType = contentType;
} /// <summary>
/// 设置Cookie
/// </summary>
/// <param name="cookie"></param>
public void SetCookie(CookieContainer cookie)
{
this.cookie = cookie;
}
/// <summary>
/// 是否允许重定向(默认:true)
/// </summary>
/// <param name="allowAutoRedirect"></param>
public void SetIsAllowAutoRedirect(bool allowAutoRedirect)
{
this.allowAutoRedirect = allowAutoRedirect;
} /// <summary>
/// post请求返回html
/// </summary>
/// <param name="url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public string HttpPost(string url, Dictionary<string, string> postdata)
{
string postDataStr = null;
if (postdata != null && postdata.Count > 0)
{
postDataStr = string.Join("&", postdata.Select(it => it.Key + "=" + it.Value));
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = allowAutoRedirect;
request.Method = "POST";
request.Accept = accept;
request.ContentType = this.contentType;
request.Timeout = time;
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
if (cookie != null)
request.CookieContainer = cookie; //cookie信息由CookieContainer自行维护
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = null;
try
{
this.SetCertificatePolicy();
response = (HttpWebResponse)request.GetResponse();
}
catch (System.Exception ex)
{
throw ex;
}
//获取重定向地址
//string url1 = response.Headers["Location"];
if (response != null)
{
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
else
{
return null; //post请求返回为空
}
}
/// <summary>
/// get请求获取返回的html
/// </summary>
/// <param name="url">无参URL</param>
/// <param name="querydata">参数</param>
/// <returns></returns>
public string HttpGet(string url, Dictionary<string, string> querydata)
{
if (querydata != null && querydata.Count > 0)
{
url += "?" + string.Join("&", querydata.Select(it => it.Key + "=" + it.Value));
} return HttpGet(url);
}
/// <summary>
/// get请求获取返回的html
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string HttpGet(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.CookieContainer = cookie;
request.Accept = this.accept;
request.Timeout = time;
this.SetCertificatePolicy();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// response.Cookies = cookie.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
} /// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="file">文件路径</param>
/// <param name="postdata"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string file, Dictionary<string, string> postdata)
{
return HttpUploadFile(url, file, postdata, Encoding.UTF8);
}
/// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="file">文件路径</param>
/// <param name="postdata">参数</param>
/// <param name="encoding"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string file, Dictionary<string, string> postdata, Encoding encoding)
{
return HttpUploadFile(url, new string[] { file }, postdata, encoding);
}
/// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="files">文件路径</param>
/// <param name="postdata">参数</param>
/// <returns></returns>
public string HttpUploadFile(string url, string[] files, Dictionary<string, string> postdata)
{
return HttpUploadFile(url, files, postdata, Encoding.UTF8);
}
/// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="files">文件路径</param>
/// <param name="postdata">参数</param>
/// <param name="encoding"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string[] files, Dictionary<string, string> postdata, Encoding encoding)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); //1.HttpWebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Accept = this.accept;
request.Timeout = this.time;
request.AllowAutoRedirect = this.allowAutoRedirect;
if (cookie != null)
request.CookieContainer = cookie;
request.Credentials = CredentialCache.DefaultCredentials; using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (postdata != null)
{
foreach (string key in postdata.Keys)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, postdata[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, 0, formitembytes.Length);
}
} //1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[4096];
int bytesRead = 0;
for (int i = 0; i < files.Length; i++)
{
stream.Write(boundarybytes, 0, boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
}
} //1.3 form end
stream.Write(endbytes, 0, endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
} /// <summary>
/// 获得响应中的图像
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public Stream GetResponseImage(string url)
{
Stream resst = null;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = true;
req.Method = "GET";
req.AllowAutoRedirect = allowAutoRedirect;
req.CookieContainer = cookie;
req.ContentType = this.contentType;
req.Accept = this.accept;
req.Timeout = time;
Encoding myEncoding = Encoding.GetEncoding("UTF-8");
this.SetCertificatePolicy();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
resst = res.GetResponseStream();
return resst;
}
catch
{
return null;
}
}
/// <summary>
/// 正则获取匹配的第一个值
/// </summary>
/// <param name="html"></param>
/// <param name="pattern"></param>
/// <returns></returns>
private string GetStringByRegex(string html, string pattern)
{
Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matchs = re.Matches(html);
if (matchs.Count > 0)
{
return matchs[0].Groups[1].Value;
}
else
return "";
}
/// <summary>
/// 正则验证返回的response是否正确
/// </summary>
/// <param name="html"></param>
/// <param name="pattern"></param>
/// <returns></returns>
private bool VerifyResponseHtml(string html, string pattern)
{
Regex re = new Regex(pattern);
return re.IsMatch(html);
}
//注册证书验证回调事件,在请求之前注册
private void SetCertificatePolicy()
{
ServicePointManager.ServerCertificateValidationCallback
+= RemoteCertificateValidate;
}
/// <summary>
/// 远程证书验证,固定返回true
/// </summary>
private static bool RemoteCertificateValidate(object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
return true;
}
}
}
ASP.NET HTTP模拟提交通用类 GET POST的更多相关文章
- 反射+泛型+缓存 ASP.NET的数据层通用类
using System; using System.Collections.Generic; using System.Text; using System.Reflection ; using S ...
- asp.net core 3.x 通用主机原理及使用
一.前言 只是讲asp.net core 3.x通用主机的大致原理,这些东西是通过查看源码以及自己根据经验总结得来的,在文章中不会深入源码,因为个人觉得懂原理就晓得扩展点,后期碰到有需求的时候再仔细去 ...
- 模拟提交API数据Pyqt版
其实这个模拟提交数据之前已经写过篇: Python requests模拟登录 因为现在在做的项目中需要一个debug请求调试API,用PHP的CURL写了一个,又因Pyqt更能直观灵活的显示请求的参数 ...
- .Net模拟提交表单
2016-09-0210:49:20 以中邮速递API为服务接口,由于提交方式为表单提交,我要获取返回值来处理其他业务,所以一开始尝试采用Js后台获取返回值,但是涉及到跨域请求限制问题,那边服务端接口 ...
- C# 模拟提交带附件(input type=file)的表单
今天调用某API时,对于文档中的传入参数:File[] 类型,感觉很陌生,无从下手! 按通常的方式在json参数中加入file的二进制数据提交,一直报错(参数错误)!后来经过多方咨询,是要换一种 表单 ...
- 网络爬虫入门(二)模拟提交以及HttpClient修正
模拟提交就是说我们不自己登陆到客户端,仅仅靠发送请求就模拟了客户端的操作,在现实使用的时候经常用来接收一些需要登录才能获取到的数据,来模拟表单的提交,所以很多时候也被称作虚拟登录,这次的例子是我自己为 ...
- asp.net core 3.x 通用主机是如何承载asp.net core的-上
一.前言 上一篇<asp.net core 3.x 通用主机原理及使用>扯了下3.x中的通用主机,刚好有哥们写了篇<.NET Core 3.1和WorkerServices构建Win ...
- poi导出excel通用类
一.关键的通用类public class PoiExportUtils { private static HSSFWorkbook workBook; public PoiExportUtils ...
- NPOI MVC 模型导出Excel通用类
通用类: public enum DataTypeEnum { Int = , Float = , Double = , String = , DateTime = , Date = } public ...
随机推荐
- js 排列 组合 的一个简单例子
最近工作项目需要用到js排列组合,于是就写了一个简单的demo. 前几天在网上找到一个写全排列A(n,n)的code感觉还可以,于是贴出来了, 排列的实现方式: 全排列主要用到的是递归和数组的插入 比 ...
- 收不到Win10正式版预订通知?一个批处理搞定
目前,已经有不少Win7.Win8.1用户在系统右下角收到Win10正式版的预订提示窗口.点击接受预订后,系统会将Win10正式版所需的安装文件提前下载好,7月29日正式发布的时候,就可以第一时间升级 ...
- android通话时第二通电话呼叫等待提示音音量大小
callnotifier.java public void run() { ...... switch (mToneId) { case TO ...
- 关于VS2010出现“此方法显式使用的 CAS 策略已被 .NET Framework 弃用... ...请使用 NetFx40_LegacySecurityPolicy 配置开关”解决办法
有时候VS会出现“此方法显式使用的 CAS 策略已被 .NET Framework 弃用.若要出于兼容性原因而启用 CAS 策略,请使用 NetFx40_LegacySecurityPolicy 配置 ...
- C# Activex开发、打包、签名、发布 C# Activex开发、打包、签名、发布 [转]
C# Activex开发.打包.签名.发布 2013-06-22 12:01:20 浏览:3823 一.前言 最近有这样一个需求,需要在网页上面启动客户端的软件,软件之间的通信.调用,单单依靠HTML ...
- A Simple MVVM Example[Forward]
In my opinion, if you are using WPF or Silverlight you should be using the MVVM design pattern. It i ...
- 关于移动App的五个提问
1.你的移动App利用了手机的哪些特性? 2.你们是否有用移动的角度和思维来考虑产品形态?还是简单的把Web照搬到手机上? 3.用户有什么特殊的动力去安装你们的App? 4.用户是否能很好的上手和使用 ...
- josephus Problem 中级(使用数组模拟链表,提升效率)
问题描写叙述: 在<josephus Problem 0基础(使用数组)>中.我们提出了一种最简单直接的解决方式. 可是,细致审视代码之后.发现此种方案的效率并不高,详细体如今.当有人出局 ...
- notepad++插件
html插件 https://github.com/downloads/davegb3/NppTidy2/Tidy2_0.2.zip
- 电商O2O-11种最佳运营模式
免费模式,是在这种矛盾下应运而生的新型模式.免费模式在未来的几年中,将会不断的渗透到各个行业中,这不单单是加速了行业内部的洗牌速度,更是加速了行业之间的洗牌速度. 未来,免费模式会让行业之间的界限变得 ...