In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how to use HttpWebRequest, WebClient and HttpClient in C#. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
HttpWebRequest:
Namespace: System.Net, a standard class originally developed by .NET creators for using HTTP requests. Using HttpWebRequest allows developers to control all aspects of the request / response process, such as timeouts, cookies, headers, protocols. Another benefit is that the HttpWebRequest class does not block UI threads. For example, when you download a large file from a slow API server, your application's UI does not stop responding. HttpWebRequest is usually used with WebResponse, one to send a request and one to get data. HttpWebRquest is more low-level and can have an intuitive understanding of the whole visit process, but it is also a little more complex.
/ / POST method public static string HttpPost (string Url, string postDataStr) {HttpWebRequest request = (HttpWebRequest) WebRequest.Create (Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; Encoding encoding = Encoding.UTF8; byte [] postData = encoding.GetBytes (postDataStr); request.ContentLength = postData.Length; Stream myRequestStream = request.GetRequestStream (); myRequestStream.Write (postData, 0, postData.Length); myRequestStream.Close (); HttpWebResponse response = (HttpWebResponse) request.GetResponse () Stream myResponseStream = response.GetResponseStream (); StreamReader myStreamReader = new StreamReader (myResponseStream, encoding); string retString = myStreamReader.ReadToEnd (); myStreamReader.Close (); myResponseStream.Close (); return retString;} / / GET method public static string HttpGet (string Url, string postDataStr) {HttpWebRequest request = (HttpWebRequest) WebRequest.Create (Url + (postDataStr = "?": ") + postDataStr); request.Method =" GET "; request.ContentType =" text/html;charset=UTF-8 "; HttpWebResponse response = (HttpWebResponse) request.GetResponse () Stream myResponseStream = response.GetResponseStream (); StreamReader myStreamReader = new StreamReader (myResponseStream, Encoding.GetEncoding ("utf-8")); string retString = myStreamReader.ReadToEnd (); myStreamReader.Close (); myResponseStream.Close (); return retString;}
WebClient:
The namespace System.Net,WebClient is a higher-level abstraction created by HttpWebRequest to simplify the most common tasks. You will find that it lacks basic header,timeoust settings during use, but this can be achieved by inheriting httpwebrequest. Relatively speaking, WebClient is simpler than WebRequest, which is equivalent to encapsulating request and response methods, but it is important to note that Webclient and WebRequest inherit different classes, and there is no inheritance relationship between them. Using WebClient may be slower than using HttpWebRequest directly (about a few milliseconds), but it is simpler, reduces a lot of detail, and requires less code.
Public class WebClientHelper {public static string DownloadString (string url) {WebClient wc = new WebClient (); / / wc.BaseAddress = url; / / set root directory wc.Encoding = Encoding.UTF8; / / set according to what code to access. If this line is not added, the Chinese character of the obtained string will be garbled string str = wc.DownloadString (url); return str;} public static string DownloadStreamString (string url) {WebClient wc = new WebClient () Wc.Headers.Add ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"); Stream objStream = wc.OpenRead (url); StreamReader _ read = new StreamReader (objStream, Encoding.UTF8); / / create a new read stream and read it with the specified encoding, where utf-8 string str = _ read.ReadToEnd (); objStream.Close (); _ read.Close () Return str;} public static void DownloadFile (string url, string filename) {WebClient wc = new WebClient (); wc.DownloadFile (url, filename); / / download file} public static void DownloadData (string url, string filename) {WebClient wc = new WebClient (); byte [] bytes = wc.DownloadData (url); / / download to byte array FileStream fs = new FileStream (filename, FileMode.Create); fs.Write (bytes, 0, bytes.Length); fs.Flush (); fs.Close () } public static void DownloadFileAsync (string url, string filename) {WebClient wc = new WebClient (); wc.DownloadFileCompleted + = DownCompletedEventHandler; wc.DownloadFileAsync (new Uri (url), filename); Console.WriteLine ("downloading.") ;} private static void DownCompletedEventHandler (object sender, AsyncCompletedEventArgs e) {Console.WriteLine (sender.ToString ()); / / the object that triggered the event Console.WriteLine (e.UserState); Console.WriteLine (e.Cancelled); Console.WriteLine ("Asynchronous download completed!") ;} public static void DownloadFileAsync2 (string url, string filename) {WebClient wc = new WebClient (); wc.DownloadFileCompleted + = (sender, e) = > {Console.WriteLine ("download complete!"); Console.WriteLine (sender.ToString ()); Console.WriteLine (e.UserState); Console.WriteLine (e.Cancelled);}; wc.DownloadFileAsync (new Uri (url), filename); Console.WriteLine ("downloading.") ;}}
HttpClient:
HttpClient is a HTTP client library introduced in .NET 4.5 with a namespace of System.Net.Http, and we may have used WebClient and HttpWebRequest to achieve the same purpose before .NET4.5. HttpClient takes advantage of the latest task-oriented pattern, which makes it easy to handle asynchronous requests. It is suitable for multiple request operations. Generally, after the default header is set, you can make repeated requests. Basically, any HTTP request can be submitted with an instance. HttpClient has a warm-up mechanism, which is slow to access for the first time, so you should not use HttpClient to new alone. Instead, you should use singletons or other methods to obtain instances of HttpClient.
Singleton mode:
Singleton patterns (Singleton Pattern), a type of design pattern that belongs to the creative pattern, provides the best way to create objects.
This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique object directly without instantiating the object of the class.
Steps to create a singleton: 1, define static private objects; 2, define private constructors; 3, provide public access object methods
The singleton pattern is generally divided into two implementation modes: lazy mode and hungry mode (the following is the Java code implementation)
Lazy mode: it will not be instantiated by default, and when to use new
Public class Singleton {private static Singleton instance = null; private Singleton () {} public static Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance;}}
This is the most basic implementation, and the biggest problem with this implementation is that it does not support multithreading. Because synchronized is not locked, it is not strictly a singleton pattern. In this way, lazy loading is obvious, does not require thread safety, and does not work properly in multithreading.
Hungry mode: when the class is initialized, the object is loaded immediately. The thread is inherently safe and the call efficiency is high.
Public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;}}
Double check lock / double check lock (DCL, that is, double-checked locking): this approach adopts double lock mechanism, which is safe and can maintain high performance in the case of multi-thread.
Public class Singleton {private volatile static Singleton singleton; private Singleton () {} public static Singleton getSingleton () {if (singleton = = null) {synchronized (Singleton.class) {if (singleton = = null) {singleton = new Singleton ();} return singleton;}}
HttpClient:
Public class HttpClientHelper {private static readonly object LockObj = new object (); private static HttpClient client = null; public HttpClientHelper () {GetInstance ();} public static HttpClient GetInstance () {if (client = = null) {lock (LockObj) {if (client = = null) {client = new HttpClient ();} return client;} public async Task PostAsync (string url, string strJson) / / post Asynchronous request method {try {HttpContent content = new StringContent (strJson) Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json"); / / Asynchronous Post requests issued by HttpClient HttpResponseMessage res = await client.PostAsync (url, content); if (res.StatusCode = = System.Net.HttpStatusCode.OK) {string str = res.Content.ReadAsStringAsync (). Result; return str;} else return null;} catch (Exception ex) {return null }} public string Post (string url, string strJson) / / post synchronous request method {try {HttpContent content = new StringContent (strJson); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json"); / / client.DefaultRequestHeaders.Connection.Add ("keep-alive"); / / Post request Task res = client.PostAsync (url, content) issued by HttpClient If (res.Result.StatusCode = = System.Net.HttpStatusCode.OK) {string str = res.Result.Content.ReadAsStringAsync (). Result; return str;} else return null;} catch (Exception ex) {return null;}} public string Get (string url) {try {var responseString = client.GetStringAsync (url); return responseString.Result;} catch (Exception ex) {return null;}
HttpClient has a prefetch mechanism, so the first request is slow. You can solve this problem by sending a head request before initialization:
_ httpClient = new HttpClient () {BaseAddress = new Uri (BASE_ADDRESS)}; / / warm up HttpClient _ httpClient.SendAsync (new HttpRequestMessage {Method = new HttpMethod ("HEAD"), RequestUri = new Uri (BASE_ADDRESS + "/")}) .Result.EnsureSuccessStatusCode ()
Thank you for reading! This is the end of the article on "how to use HttpWebRequest, WebClient and HttpClient in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.