Knowledge of HttpWebRequest and HttpWebResponse classes __httpwebreq

Source: Internet
Author: User

1, HttpWebRequest and HttpWebResponse class
The HttpWebRequest and HttpWebResponse classes are the best choice for sending and receiving HTTP data. They support a range of useful properties. These two classes are in the System.Net namespace, and by default this class is accessible to the console program. Note that the HttpWebRequest object is not created using the New keyword through a constructor, but instead is created using a factory mechanism (factory mechanism) through the Create () method. The next call to the HttpWebRequest.GetResponse () method returns a HttpWebResponse object. Mine is to bind the HTTP response data stream (stream) to a StreamReader object, and then you can retrieve the entire HTTP response as a string through the ReadToEnd () method. However, you can also retrieve the contents of the HTTP response line by row in the StreamReader.ReadLine () method.
2. Properties and methods used by the HttpWebRequest and HttpWebResponse classes
2.1 HttpWebRequest Properties
CharacterSet gets the character set of the response.
ContentEncoding gets the method that is used to encode the response body.
ContentLength gets the length of the content returned by the request.
ContentType gets the content type of the response.
Cookies Gets or sets the Cookie associated with this response.
Headers gets the headers from the server that are associated with this response.
Isfromcache gets a Boolean value that indicates whether this response was obtained from the cache.
Ismutuallyauthenticated gets a Boolean value that indicates whether both the client and the server have been authenticated.
LastModified Gets the date and time when the response content was last modified.
Method gets the methods that are used to return the response.
ProtocolVersion gets the version of the HTTP protocol used in the response.
ResponseUri gets the URI of the Internet resource that responds to the request.
Gets the name of the server that sent the response.
StatusCode gets the state of the response.
Statusdescription Gets the status description that is returned with the response.
2.2 HttpWebRequest Properties
Close closes the response stream.
Dispose frees the unmanaged resources that are used by HttpWebResponse and releases the managed resources as needed.
getResponseHeader gets the contents of the header returned with the response.
GetResponseStream gets the stream that is used to read the body of the response from the server.
InitializeLifetimeService Gets the lifetime service object that controls the lifetime policy for this instance.
2.3, HttpWebResponse property
Buffer Gets or sets a value that indicates whether to buffer the output and send it after the entire response has been processed.
BufferOutput Gets or sets a value that indicates whether to buffer the output and send it after the entire page has been processed.
Cache Gets the caching policy for the Web page (for example: Expiration time, privacy settings, and change terms).
CacheControl Gets or sets the Cache-control HTTP header that matches one of the HttpCacheability enumeration values.
Charset Gets or sets the HTTP character set for the output stream.
ContentEncoding Gets or sets the HTTP character set for the output stream.
ContentType Gets or sets the HTTP MIME type of the output stream.
Cookies get a collection of response cookies.
Expires Gets or sets the number of minutes before the cached page expires in the browser. If the user returns the same page before the page expires, the cached version is displayed. Expires is provided to maintain compatibility with previous versions of ASP.
ExpiresAbsolute Gets or sets the absolute date and time when cached information is removed from the cache. ExpiresAbsolute is provided to maintain compatibility with previous versions of ASP.
Filter Gets or sets a wrapper filter object that is used to modify the HTTP entity body before the transfer.
Headerencoding Gets or sets an Encoding object that represents the encoding of the current header output stream.
Headers gets the collection of response headers.
IsClientConnected Gets a value indicating whether the client is still connected to the server.
Isrequestbeingredirected gets a Boolean value that indicates whether the client is being transferred to a new location.
Output enables text output to the output HTTP response stream.
OutputStream enables binary output to the output HTTP content body.
Redirectlocation Gets or sets the value of the Http Location header.
The status setting returns to the status bar of the client.
StatusCode Gets or sets the HTTP status code of the output returned to the client.
Statusdescription Gets or sets the HTTP status string of the output returned to the client.
Substatuscode Gets or sets the value of the status code for a qualifying response.
Suppresscontent Gets or sets a value that indicates whether HTTP content is sent to the client.
Tryskipiiscustomerrors Gets or sets a value that specifies whether to disable IIS 7.0 custom errors.
2.4, HttpWebResponse method
BinaryWrite writes a binary string to the HTTP output stream.
Clear clears all content output in the buffer stream.
ClearContent clears all content output in the buffer stream.
ClearHeaders clears all headers in the buffer stream.
Close closes the socket connection to the client.
Disablekernelcache disables the kernel cache for the current response.
End sends all current buffered output to the client, stops execution of the page, and raises the EndRequest event.
Flush sends all current buffered output to the client.
Pics appends an HTTP Pics-label header to the output stream.
Redirect has been overloaded. Redirects the client to the new URL.
RemoveOutputCacheItem removes all cached entries associated with the specified path from the cache. This method is static.
Setcookie infrastructure. Updates an existing cookie in the cookie collection.
TransmitFile has been overloaded. Writes the specified file directly to the HTTP response output stream, rather than buffering the file in memory.
Write has been overloaded. Writes information to the HTTP response output stream.
WriteFile has been overloaded. Writes the specified file directly to the HTTP response output stream.
WriteSubstitution allows the response substitution block to be inserted into the response, allowing the specified response region to be dynamically generated for the cached output response.

3, the httppos of the following

 public static string HttpPost (string URL, string data) {if (url = "") return ""; try {servicepointmanager.servercertificatevalidationcallback =new remotecertificat
                Evalidationcallback (CheckValidationResult);
                HttpWebRequest request = (HttpWebRequest) httpwebrequest.create (URL); Request.
                method = "POST"; Request. ContentType = "application/x-www-form-urlencoded;
                Charset=utf-8 "; if (!string.
                    IsNullOrEmpty (data)) {byte[] byt = Encoding.UTF8.GetBytes (data); Request. ContentLength = byt.
                    Length; **//request. GetRequestStream gets the data for the write request * * Stream sr = Request.
                    GetRequestStream (); Sr. Write (byt, 0, Byt.
                    Length); Sr.
                    Close (); Sr.
                Dispose (); } **//request. GetResponse () Returns a response from a inter resource* * HttpWebResponse response = (HttpWebResponse) request.
                GetResponse ();
                string result; **//response. GetResponseStream () The data stream returned from the Inter resource * * using (StreamReader reader = new StreamReader (response). GetResponseStream ()) {result = reader.
                    ReadToEnd (); Reader.
                Close ();
            return result; The catch (Exception ex) {Writelog (ex).
                message);
            Return ""; }
        }

the HttpGet is as follows

    public static string HttpGet (string url)
        {
            if (url = = "") return
                "";
            Try
            {
                HttpWebRequest request = (HttpWebRequest) httpwebrequest.create (URL);
                Request. method = ' Get ';
                Request. Timeout =;
                HttpWebResponse response = (HttpWebResponse) request. GetResponse ();
                string result;
                using (StreamReader sr = new StreamReader (response). GetResponseStream ())
                {result
                    = Sr. ReadToEnd ();
                    Sr. Close ();
                }
                return result;
            }
            catch (Exception ex)
            {
                writelog (ex. message);
                Return "";
            }
        }

methods called by Httpost and HttpGet

 public static void Writelog (string content) {String filepath = Path.Combine
            (AppDomain.CurrentDomain.BaseDirectory, "Tdapi.log"); Using (StreamWriter sr = new StreamWriter (filepath,true)) {string cot=string.
                Format ("{0}:{1}", DateTime.Now.ToString (), content); Sr.
                WriteLine (COT); Sr.
                Close (); }
        }

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.