Background Web request code (with Https,json submission)

Source: Internet
Author: User

Background Web request

namespaceXXXX. utilites{usingSystem; usingSystem.Collections.Generic; usingSystem.IO; usingSystem.IO.Compression; usingSystem.Net; usingSystem.Net.Security; usingSystem.Security.Cryptography.X509Certificates; usingSystem.Text;  Public classPosthttpresponse {#regionStatic FieldPrivate Static ReadOnly stringDefaultuseragent ="mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;. NET CLR 1.1.4322;. NET CLR 2.0.50727)"; #endregion        #regionPublic Method Public Static stringPosthttpresponsejson (stringURL) {            stringJSON =string.            Empty; Encoding Encoding=Encoding.UTF8; HttpWebResponse Response= Createposthttpresponsejson (URL,NULL,NULL,NULL,NULL, Encoding,NULL); JSON=GetStream (Response, encoding); returnJSON; }         Public Static stringPosthttpresponsejson (stringUrlstringPostjson) {            stringJSON =string.            Empty; Encoding Encoding=Encoding.UTF8; HttpWebResponse Response= Createposthttpresponsejson (URL, Postjson,NULL,NULL,NULL, Encoding,NULL); JSON=GetStream (Response, encoding); returnJSON; }           /// <summary>        ///create HTTP requests for post-mode JSON data (including HTTPS site requests)/// </summary>        /// <param name= "url" >the requested URL</param>        /// <param name= "Parameters" >Dictionary of parameter names and parameter values accompanying the request post</param>        /// <param name= "Timeout" >Request time-out</param>        /// <param name= "useragent" >requested client browser information, can be empty</param>        /// <param name= "requestencoding" >encoding used when sending an HTTP request</param>        /// <param name= "cookies" >cookie information sent with an HTTP request, if authentication is not required can be null</param>        /// <returns></returns>         Public StaticHttpWebResponse Createposthttpresponsejson (stringUrlstringPostjson,stringParametersint? TimeoutstringUserAgent, Encoding requestencoding,stringreferer) {            if(string. IsNullOrEmpty (URL)) {Throw NewArgumentNullException ("URL"); }            if(requestencoding = =NULL)            {                Throw NewArgumentNullException ("requestencoding"); } HttpWebRequest Request=NULL; //If you are sending an HTTPS request            if(URL.) StartsWith ("HTTPS", StringComparison.OrdinalIgnoreCase)) {Servicepointmanager.servercertificatevalidationcallback=NewRemotecertificatevalidationcallback (CheckValidationResult); Request= WebRequest.Create (URL) asHttpWebRequest; Request. ProtocolVersion=Httpversion.version10; }            Else{Request= WebRequest.Create (URL) asHttpWebRequest; } request. Method="POST"; //when the server determines whether the client is submitting JSON dataRequest. ContentType ="Application/json;charset=utf-8"; Request. KeepAlive=true; if(!string. IsNullOrEmpty (useragent)) {request. UserAgent=useragent; }            Else{request. UserAgent=defaultuseragent; }            if(timeout. HasValue) {request. Timeout=timeout.            Value; }            //If you need post data            #regionPost parameter similar to QueryString formatif(Parameters! =NULL)            {                byte[] data =requestencoding.getbytes (parameters); using(Stream stream =request. GetRequestStream ()) {stream. Write (data,0, data.                    Length); Stream.                Close (); }            }            #endregion            #regionPost JSONif(!string. IsNullOrEmpty (Postjson)) {using(varStreamWriter =NewStreamWriter (Request. GetRequestStream ())) {//string json = "{\" user\ ": \" test\ "," +//"\" password\ ": \" Bla\ "}";StreamWriter.Write (Postjson);                    StreamWriter.Flush ();                StreamWriter.Close (); }            }            #endregion            if(!string. IsNullOrEmpty (Referer)) {request. Referer=Referer; } HttpWebResponse Response= Request. GetResponse () asHttpWebResponse; if(Request. Cookiecontainer! =NULL) {Response. Cookies=request. Cookiecontainer.getcookies (Request.            RequestUri); }            returnresponse; }        #endregion        #regionPrivate MethodPrivate Static BOOLCheckValidationResult (Objectsender, X509Certificate certificate, X509chain chain, sslpolicyerrors errors) {            return true;//Always accept        }        /// <summary>        ///Convert response to text/// </summary>        /// <param name= "Response" ></param>        /// <param name= "encoding" ></param>        /// <returns></returns>        Private Static stringGetStream (httpwebresponse response, Encoding Encoding) {Try            {                if(Response. StatusCode = =Httpstatuscode.ok) {Switch(response. Contentencoding.tolower ()) { Case "gzip":                            {                                stringresult =Decompress (response.                                GetResponseStream (), encoding); Response.                                Close (); returnresult; }                        default:                            {                                using(StreamReader sr =NewStreamReader (response. GetResponseStream (), encoding)) {stringresult =Sr.                                    ReadToEnd (); Sr.                                    Close (); Sr.                                    Dispose (); Response.                                    Close (); returnresult; }                            }                    }                }                Else{Response.                Close (); }            }            Catch(Exception e) {Throwe; }            return ""; }        Private Static stringDecompress (Stream stream, Encoding Encoding) {byte[] buffer =New byte[ -]; //int length = 0;            using(GZipStream GZ =NewGZipStream (Stream, compressionmode.decompress)) {                //GZipStream gzip = new GZipStream (res. GetResponseStream (), compressionmode.decompress);                using(StreamReader reader =NewStreamReader (GZ, encoding)) {                    returnReader.                ReadToEnd (); }                /*using (MemoryStream mstemp = new MemoryStream ()) {//extracted directly with the Read method Content, you cannot invoke properties such as length of the GZipStream instance, otherwise an error occurs: System.NotSupportedException: This operation is not supported, while (length = gz. Read (buffer, 0, buffer.                    Length))! = 0) {mstemp.write (buffer, 0, length); } return encoding.                GetString (Mstemp.toarray ()); }                 * */            }        }        #endregion    }}

Background Web request code (with Https,json submission)

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.