ASP. net http analog submission common class get post, asp. netget

Source: Internet
Author: User
Tags set cookie

ASP. net http analog submission common class get post, asp. netget

Usage:

WebRequestSugar ws = new WebRequestSugar (); // optional parameter // 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 "," the file address can be an array ", paras );

  

 

Class:

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> /// ** Description: Simulate an http post get request and obtain data. // ** Creation Time: // ** modification time:-// ** Author: sunkaixuan /// ** Usage instructions: // </summary> public class WebRequestSugar {// <summary> // set cookie // </summary> private CookieContainer cookie; /// <summary> /// whether redirection is allowed /// </summary> private bool allowAutoRedirect = true; /// <summary> /// contentType /// </summary> private string contentType = "application/x-www-form-urlencoded "; /// <summary> // accept // </summary> private string accept = "*/*"; // <sum Mary> // expiration time /// </summary> private int time = 5000; // <summary> // set the request expiration time (unit: milliseconds) (default: 5000) /// </summary> /// <param name = "time"> </param> public void SetTimeOut (int time) {this. time = time ;}/// <summary> /// set accept (default :*/*) /// </summary> /// <param name = "accept"> </param> public void SetAccept (string accept) {this. accept = accept;} // <summary> // sets the contentType (default: application/x-www- Form-urlencoded) /// </summary> /// <param name = "contentType"> </param> public void SetContentType (string contentType) {this. contentType = contentType ;} /// <summary> /// set Cookie /// </summary> /// <param name = "cookie"> </param> public void SetCookie (CookieContainer cookie) {this. cookie = cookie;} // <summary> // whether to allow redirection (default: true) /// </summary> /// <param name = "allowAutoRedirect"> </param> pub Lic void SetIsAllowAutoRedirect (bool allowAutoRedirect) {this. allowAutoRedirect = allowAutoRedirect ;} /// <summary> /// the post request returns 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 (postDataSt R); if (cookie! = Null) request. cookieContainer = cookie; // The cookie information is maintained by 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;} // get the redirection address // 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; // The returned result of the post request is null }}/// <summary> /// get request to obtain the returned html /// </summary> /// <param name = "url"> No parameter URL </param> /// <Param name = "querydata"> parameter </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 request to obtain the returned 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 = co Okie; request. accept = this. accept; request. timeout = time; this. setCertificatePolicy (); HttpWebResponse response = (HttpWebResponse) request. getResponse (); // response. cookies = Cookies. getCookies (response. responseUri); Stream myResponseStream = response. getResponseStream (); StreamReader myStreamReader = new StreamReader (myResponseStream, Encoding. getEncoding ("UTF-8"); string retString = myStreamR Eader. readToEnd (); myStreamReader. close (); myResponseStream. close (); return retString ;} /// <summary> // POST File // </summary> /// <param name = "url"> </param> /// <param name = "file"> file path </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 File // </summary> /// <param name = "url"> </param> /// <param name = "file"> file path </param> /// <param name = "postdata"> parameter </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 File // </summary> /// <param name = "url"> </param> /// <param name = "files"> file path </param> /// <param name = "postdata"> parameter </param> /// <returns> </returns> public string HttpUploadFile (string url, string [] files, Dictionary <string, string> postdata) {return HttpUploadFile (url, files, postdata, Encoding. UTF8);} // <summary> // POST File // </summary> // <param name = "url"> </param>/ // <Param name = "files"> file path </param> /// <param name = "postdata"> parameter </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 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; I F (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 {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 "; 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> /// obtain the image in the response /// </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> /// obtain the first value of the matching Regular Expression // </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> /// check whether the response returned by regular expression verification is correct /// </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);} // register a certificate verification callback event. Register private void SetCertificatePolicy () {ServicePointManager before the request. certificate + = RemoteCertificateValidate;} /// <summary> // for remote certificate verification, fixed return true /// </summary> private static bool RemoteCertificateValidate (object sender, X509Certificate cert, x509Chain chain, SslPolicyErrors error) {return true ;}}}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.