A good C # Http/https class

Source: Internet
Author: User

Direct copy to use it :

The new TLS protocol requires a new. NET version, and TLS is updated at least to. Net4, try to use the latest. net! Otherwise the error is to toss ...

Using system;using system.collections.generic;using system.linq;using system.text;using System.Net.Security;using System.security.cryptography.x509certificates;using system.servicemodel.security;using System.Net;using System.IO ; using system.io.compression;using system.text.regularexpressions;namespace lzp.service{//<summary>//        Auxiliary class for HTTP/HTTPS request Lzpong///default UTF-8 code///</summary> public class HTTPS {public HTTPS ()            {SPT = Securityprotocoltype.tls;            requestencoding = encoding.getencoding ("UTF-8");        Requestuseragent = defaultuseragent; }///<summary>///Securityprotocoltype If HTTPS appears "base connection ..." or "SSL/TLS ..." error, change this property;        You may also need to upgrade. NET has support for updated security protocols///</summary> public static Securityprotocoltype SPT {get; set;}        Set encoding default encoding is UTF-8 public static Encoding requestencoding {get; set;} Set encoding public static void Setencoding (sTring endcode) {requestencoding = encoding.getencoding (Endcode);}        private static string requestuseragent = Defaultuseragent; private static readonly string defaultuseragent = "mozilla/5.0 (Windows NT 6.1;        WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/45.0.2454.101 safari/537.36 "; Set the browser version public static void Setuseragent (string useragent = null) {if (! String.isnullorwhitespace (useragent)) requestuseragent = useragent; else requestuseragent = defaultuseragent; }///<summary>//Create a Get method Http/https request///</summary>//<param name= "url" &G t; requested url</param>//<param name= "Timeout" > timeout for request </param>//<param name= "useragent" & GT; Requested client browser information, can be null </param>///<param Name= "requestencoding" > Encoding used to send HTTP requests </param>////        Lt;param name= "Cookies" > Cookie information sent with HTTP requests, if authentication is not required can be null </param>//<returns></returns> Public sTatic httpwebresponse createget (string url, int? timeout = null, string useragent = null, cookiecollection cookie = null)        {return Create (URL, null, "GET", requestencoding, timeout, cookies); }///<summary>//Http/https request to create POST method///</summary>//<param name= "url" & gt; requested url</param>//<param name= "parameters" > data accompanying the request for post </param>//<param name= "Tim Eout "> Timeout for request </param>//<param name=" useragent "> requested client browser information, can be null </param>//<para M name= "requestencoding" > Encoding used to send HTTP requests </param>//<param name= "cookies" > Cookie information sent with HTTP requests, if not required Authentication can be null </param>///<returns></returns> public static HttpWebResponse Createpost (String u RL, string parameters = null, int? Timeout = null, cookiecollection cookies = null) {return Create (URL, parameters, "POST", Requestencodin G, timeout, cookIES); }///<summary>//Create HTTP/HTTPS request///</summary>//<param name= "url" > Requested U rl</param>//<param name= "Parameters" > a dictionary of parameter names and parameter values accompanying the request post </param>//<param name= "Ti Meout "> Timeout for request </param>//<param name=" useragent "> requested client browser information, can be null </param>//<par Am Name= "requestencoding" > Encoding used to send HTTP requests </param>//<param name= "cookies" > Cookie information sent with HTTP requests, if not required  To authenticate can be null </param>////<returns></returns> public static HttpWebResponse Create (string URL, String Parameters=null, String method = "GET", Encoding requestencoding = null, int? Timeout = null, cookiecollection cookie = null) {if (string.            IsNullOrEmpty (URL)) throw new ArgumentNullException ("url");            if (requestencoding = = null) requestencoding=encoding.getencoding ("UTF-8"); HttpWebRequest request = Null If the HTTPS request is sent if (URL. StartsWith ("https", StringComparison.OrdinalIgnoreCase)) {Servicepointmanager.securityprotocol                = SPT; Servicepointmanager.servercertificatevalidationcallback = new Remotecertificatevalidationcallback (                CheckValidationResult);                Request = WebRequest.Create (URL) as HttpWebRequest; Request.            ProtocolVersion = Httpversion.version10;            } Else Request = WebRequest.Create (URL) as HttpWebRequest; Request.            Method = method; Request.            useragent = requestuseragent; if (timeout. HasValue) Request. Timeout = timeout.            Value; if (cookie = null) {request.                Cookiecontainer = new Cookiecontainer (); Request.            Cookiecontainer.add (cookies); }//If you need post data if (method = = "Post") {request. ContentType = "APPlication/x-www-form-urlencoded "; if (! String.isnullorwhitespace (Parameters)) {byte[] data = Requestencoding.getbytes (paramete                    RS); using (Stream stream = Request. GetRequestStream ()) {stream. Write (data, 0, data.                    Length); }}} return request.        GetResponse () as HttpWebResponse; } private static bool CheckValidationResult (object sender, X509Certificate certificate, X509chain chain, Sslpolicye Rrors errors) {return true;//Always Accept}}}

Of course, there is a web-based, but also self-tuning optimized , so or mine

Reprint should indicate http://home.cnblogs.com/u/lzpong/

A good C # Http/https class

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.