C # simulate the Http/Https request framework class,

Source: Internet
Author: User

C # simulate the Http/Https request framework class,

Using System. Text;
Using System. Net;
Using System. IO;
Using System. Text. RegularExpressions;
Using System. Security. Cryptography. X509Certificates;
Using System. Net. Security;

Namespace WebRequestTest
{
/// <Summary>
/// Dynamic class, each instance uses a separate session
/// </Summary>
Public class HttpHelperNew
{
Public CookieContainer cookie = new CookieContainer ();
/// <Summary>
/// The post request returns html
/// </Summary>
/// <Param name = "Url"> </param>
/// <Param name = "postDataStr"> </param>
/// <Returns> </returns>
Public string HttpPost (string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest) WebRequest. Create (Url );
// Request. AllowAutoRedirect = false; // disable automatic redirection
Request. Method = "POST ";
Request. ContentType = "application/x-www-form-urlencoded ";
Request. ContentLength = Encoding. UTF8.GetByteCount (postDataStr );
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)
{
}
// 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 "error"; // The returned result of the post request is null.
}

}

/// <Summary>
/// Get request to get the returned html
/// </Summary>
/// <Param name = "Url"> </param>
/// <Param name = "postDataStr"> </param>
/// <Returns> </returns>
Public string HttpGet (string Url, string Querydata)
{

HttpWebRequest request = (HttpWebRequest) WebRequest. Create (Url + (Querydata = ""? "":"? ") + Querydata );
Request. Method = "GET ";
Request. ContentType = "text/html; charsets = UTF-8 ";
Request. CookieContainer = cookie;
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>
/// Obtain the Response Image
/// </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 = true;
Req. CookieContainer = cookie;
Req. ContentType = "application/x-www-form-urlencoded ";
Req. Accept = "text/html, application/xhtml + xml, application/xml; q = 0.9, */*; q = 0.8 ";
Req. Time out = 50000;

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 a matching Regular Expression
/// </Summary>
/// <Param name = "html"> </param>
/// <Param name = "pattern"> </param>
/// <Returns> </returns>
Public 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>
/// Regular expression to verify whether the returned response is correct
/// </Summary>
/// <Param name = "html"> </param>
/// <Param name = "pattern"> </param>
/// <Returns> </returns>
Public bool verifyResponseHtml (string html, string pattern)
{
Regex re = new Regex (pattern );
Return re. IsMatch (html );
}



// Register the certificate verification callback event and register it before the request
Private void SetCertificatePolicy ()
{
ServicePointManager. ServerCertificateValidationCallback
+ = RemoteCertificateValidate;
}
/// <Summary>
/// Remote certificate verification, fixed return true
/// </Summary>
Private static bool RemoteCertificateValidate (object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
Return true;
}

}
}

Reference page:

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-user-registration.html

Http://www.yuanjiaocheng.net/mvc/filters-in-asp.net-mvc.html

Http://www.yuanjiaocheng.net/CSharp/csharp-Static.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-edit-form.html

Http://www.yuanjiaocheng.net/CSharp/csharp-linq.html

Http://www.yuanjiaocheng.net/Entity/first.html

Http://www.yuanjiaocheng.net/mvc/action-filters-in-mvc.html

Http://www.yuanjiaocheng.net/CSharp/csharp-index.html

Http://www.yuanjiaocheng.net/entity/crud-in-Disconnected.html

Http://www.yuanjiaocheng.net/CSharp/Csharp-sortedlist.html

Http://www.yuanjiaocheng.net/CSharp/csharp-action.html

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.