ASP.NETHTTP模拟提交通用类GETPOST
用法:
WebRequestSugarws=newWebRequestSugar();
//可选参数
//ws.SetAccept
//ws.SetContentType
//ws.SetCookie
//ws.SetTimeOut
//ws.SetIsAllowAutoRedirect
//GET
varhtml=ws.HttpGet("http://localhost:24587/Http/HttpTest.aspx");
//带参GET
varparas=newDictionary();
paras.Add("name","skx");
paras.Add("id","100");
varhtml2=ws.HttpGet("http://localhost:24587/Http/HttpTest.aspx",paras);
//POST
varpostHtml=ws.HttpPost("http://localhost:24587/Http/HttpTest.aspx",paras);
//postandfile
varpostHtml2=ws.HttpUploadFile("http://localhost:24587/Http/HttpTest.aspx","文件地址可以是数组",paras);
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Net;
usingSystem.IO;
usingSystem.Text.RegularExpressions;
usingSystem.Security.Cryptography.X509Certificates;
usingSystem.Net.Security;
usingSystem.Collections.Specialized;
namespaceSyntacticSugar
{
///
///描述:模拟HTTPPOSTGET请求并获取数据
///创始时间:2015-11-24
///修改时间:-
///作者:sunkaixuan
///使用说明:
///
publicclassWebRequestSugar
{
///
///设置cookie
///
privateCookieContainercookie;
///
///是否允许重定向
///
privateboolallowAutoRedirect=true;
///
///contentType
///
privatestringcontentType="application/x-www-form-urlencoded";
///
///accept
///
privatestringaccept="/";
///
///过期时间
///
privateinttime=5000;
///
///设置请求过期时间(单位:毫秒)(默认:5000)
///
///
publicvoidSetTimeOut(inttime)
{
this.time=time;
}
///
///设置accept(默认:/)
///
///
publicvoidSetAccept(stringaccept)
{
this.accept=accept;
}
///
///设置contentType(默认:application/x-www-form-urlencoded)
///
///
publicvoidSetContentType(stringcontentType)
{
this.contentType=contentType;
}
///
///设置Cookie
///
///
publicvoidSetCookie(CookieContainercookie)
{
this.cookie=cookie;
}
///
///是否允许重定向(默认:true)
///
///
publicvoidSetIsAllowAutoRedirect(boolallowAutoRedirect)
{
this.allowAutoRedirect=allowAutoRedirect;
}
///
///post请求返回html
///
///
///
///
publicstringHttpPost(stringurl,Dictionarypostdata)
{
stringpostDataStr=null;
if(postdata!=null&&postdata.Count>0)
{
postDataStr=string.Join("&",postdata.Select(it=>it.Key+"="+it.Value));
}
HttpWebRequestrequest=(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自行维护
StreammyRequestStream=request.GetRequestStream();
StreamWritermyStreamWriter=newStreamWriter(myRequestStream,Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponseresponse=null;
try
{
this.SetCertificatePolicy();
response=(HttpWebResponse)request.GetResponse();
}
catch(System.Exceptionex)
{
throwex;
}
//获取重定向地址
//stringurl1=response.Headers["Location"];
if(response!=null)
{
StreammyResponseStream=response.GetResponseStream();
StreamReadermyStreamReader=newStreamReader(myResponseStream,Encoding.GetEncoding("utf-8"));
stringretString=myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
returnretString;
}
else
{
returnnull;//post请求返回为空
}
}
///
///get请求获取返回的html
///
///无参URL
///参数
///
publicstringHttpGet(stringurl,Dictionaryquerydata)
{
if(querydata!=null&&querydata.Count>0)
{
url+="?"+string.Join("&",querydata.Select(it=>it.Key+"="+it.Value));
}
returnHttpGet(url);
}
///
///get请求获取返回的html
///
///
///
publicstringHttpGet(stringurl)
{
HttpWebRequestrequest=(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();
HttpWebResponseresponse=(HttpWebResponse)request.GetResponse();
//response.Cookies=cookie.GetCookies(response.ResponseUri);
StreammyResponseStream=response.GetResponwww.wang027.comseStream();
StreamReadermyStreamReader=newStreamReader(myResponseStream,Encoding.GetEncoding("utf-8"));
stringretString=myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
returnretString;
}
///
///POST文件
///
///
///文件路径
///
///
publicstringHttpUploadFile(stringurl,stringfile,Dictionarypostdata)
{
returnHttpUploadFile(url,file,postdata,Encoding.UTF8);
}
///
///POST文件
///
///
///文件路径
///参数
///
///
publicstringHttpUploadFile(stringurl,stringfile,Dictionarypostdata,Encodingencoding)
{
returnHttpUploadFile(url,newstring[]{file},postdata,encoding);
}
///
///POST文件
///
///
///文件路径
///参数
///
publicstringHttpUploadFile(stringurl,string[]files,Dictionarypostdata)
{
returnHttpUploadFile(url,files,postdata,Encoding.UTF8);
}
///
///POST文件
///
///
///文件路径
///参数
///
///
publicstringHttpUploadFile(stringurl,string[]files,Dictionarypostdata,Encodingencoding)
{
stringboundary="---------------------------"+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
HttpWebRequestrequest=(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(Streamstream=request.GetRequestStream())
{
//1.1key/value
stringformdataTemplate="Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}";
if(postdata!=null)
{
foreach(stringkeyinpostdata.Keys)
{
stream.Write(boundarybytes,0,boundarybytes.Length);
stringformitem=string.Format(formdataTemplate,key,postdata[key]);
byte[]formitembytes=encoding.GetBytes(formitem);
stream.Write(formitembytes,0,formitembytes.Length);
}
}
//1.2file
stringheaderTemplate="Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";
byte[]buffer=newbyte[4096];
intbytesRead=0;
for(inti=0;i {
stream.Write(boundarybytes,0,boundarybytes.Length);
stringheader=string.Format(headerTemplate,"file"+i,Path.GetFileName(files[i]));
byte[]headerbytes=encoding.GetBytes(header);
stream.Write(headerbytes,0,headerbytes.Length);
using(FileStreamfileStream=newFileStream(files[i],FileMode.Open,FileAccess.Read))
{
while((bytesRead=fileStream.Read(buffer,0,buffer.Length))!=0)
{
stream.Write(buffer,0,bytesRead);
}
}
}
//1.3formend
stream.Write(endbytes,0,endbytes.Length);
}
//2.WebResponse
HttpWebResponseresponse=(HttpWebResponse)request.GetResponse();
using(StreamReaderstream=newStreamReader(response.GetResponseStream()))
{
returnstream.ReadToEnd();
}
}
///
///获得响应中的图像
///
///
///
publicStreamGetResponseImage(stringurl)
{
Streamresst=null;
try
{
HttpWebRequestreq=(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;
EncodingmyEncoding=Encoding.GetEncoding("UTF-8");
this.SetCertificatePolicy();
HttpWebResponseres=(HttpWebResponse)req.GetResponse();
resst=res.GetResponseStream();
returnresst;
}
catch
{
returnnull;
}
}
///
///正则获取匹配的第一个值
///
///
///
///
privatestringGetStringByRegex(stringhtml,stringpattern)
{
Regexre=newRegex(pattern,RegexOptions.IgnoreCase);
MatchCollectionmatchs=re.Matches(html);
if(matchs.Count>0)
{
returnmatchs[0].Groups[1].Value;
}
else
return"";
}
///
///正则验证返回的response是否正确
///
///
///
///
privateboolVerifyResponseHtml(stringhtml,stringpattern)
{
Regexre=newRegex(pattern);
returnre.IsMatch(html);
}
//注册证书验证回调事件,在请求之前注册
privatevoidSetCertificatePolicy()
{
ServicePointManager.ServerCertificateValidationCallback
+=RemoteCertificateValidate;
}
///
///远程证书验证,固定返回true
///
privatestaticboolRemoteCertificateValidate(objectsender,X509Certificatecert,
X509Chainchain,SslPolicyErrorserror)
{
returntrue;
}
}
}
|
|