命名空间: System.Net,这是.NET创建者最初开发用于使用http请求的标准类。使用httpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts,cookies,headers, protocols。另一个好处是httpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。httpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。httpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。
//POST方法 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方法 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: 命名空间System.Net,WebClIEnt是一种更高级别的抽象,是httpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClIEnt比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,WebclIEnt和WebRequest继承的是不同类,两者在继承上没有任何关系。使用WebClIEnt可能比httpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。
public class WebClIEntHelper { public static string DownloadString(string url) { WebClIEnt wc = new WebClIEnt(); //wc.BaseAddress = url; //设置根目录 wc.EnCoding = EnCoding.UTF8; //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码 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); //新建一个读取流,用指定的编码读取,此处是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); //下载文件 } public static voID DownloadData(string url,string filename) { WebClIEnt wc = new WebClIEnt(); byte [] bytes = wc.DownloadData(url); //下载到字节数组 fileStream fs = new fileStream(filename,fileMode.Create); fs.Write(bytes,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("下载中。。。"); } private static voID DownCompletedEventHandler(object sender,AsyncCompletedEventArgs e) { Console.Writeline(sender.ToString()); //触发事件的对象 Console.Writeline(e.UserState); Console.Writeline(e.Cancelled); Console.Writeline("异步下载完成!"); } public static voID DownloadfileAsync2(string url,string filename) { WebClIEnt wc = new WebClIEnt(); wc.DownloadfileCompleted += (sender,e) => { Console.Writeline("下载完成!"); Console.Writeline(sender.ToString()); Console.Writeline(e.UserState); Console.Writeline(e.Cancelled); }; wc.DownloadfileAsync(new Uri(url),filename); Console.Writeline("下载中。。。"); } }
httpClIEnt: httpClIEnt是.NET4.5引入的一个http客户端库,其命名空间为 System.Net.http ,.NET 4.5之前我们可能使用WebClIEnt和httpWebRequest来达到相同目的。httpClIEnt利用了最新的面向任务模式,使得处理异步请求非常容易。它适合用于多次请求 *** 作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的http请求。httpClIEnt有预热机制,第一次进行访问时比较慢,所以不应该用到httpClIEnt就new一个出来,应该使用单例或其他方式获取httpClIEnt的实例
单例模式:
单例模式(Singleton Pattern)这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。
单例创建步骤:1、定义静态私有对象;2、定义私有构造函数;3、提供公共获取对象方法;
单例模式一般分为两种实现模式:懒汉模式、饿汉模式(以下为Java代码实现)
懒汉模式: 默认不会实例化,什么时候用什么时候new
public class Singleton { private static Singleton instance = null; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
这种方式是最基本的实现方式,这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,所以严格意义上它并不算单例模式。
这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。
饿汉模式: 类初始化时,会立即加载该对象,线程天生安全,调用效率高
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
双检锁/双重校验锁(DCL,即 double-checked locking):这种方式采用双锁机制,安全且在多线程情况下能保持高性能
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<string> PostAsync(string url,string strjson)//post异步请求方法 { try { httpContent content = new StringContent(strjson); content.headers.ContentType = new System.Net.http.headers.MediaTypeheaderValue("application/Json"); //由httpClIEnt发出异步Post请求 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同步请求方法 { try { httpContent content = new StringContent(strjson); content.headers.ContentType = new System.Net.http.headers.MediaTypeheaderValue("application/Json"); //clIEnt.DefaultRequestheaders.Connection.Add("keep-alive"); //由httpClIEnt发出Post请求 Task<httpResponseMessage> res = clIEnt.PostAsync(url,content); 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有预热机制,第一次请求比较慢;可以通过初始化前发送一次head请求解决:
_httpClIEnt = new httpClIEnt() { BaseAddress = new Uri(BASE_ADDRESS) }; //帮httpClIEnt热身 _httpClIEnt.SendAsync(new httpRequestMessage { Method = new httpMethod("head"),RequestUri = new Uri(BASE_ADDRESS + "/") }) .Result.EnsureSuccessstatusCode();
三者区别列表:
总结以上是内存溢出为你收集整理的C#中HttpWebRequest、WebClient、HttpClient的使用全部内容,希望文章能够帮你解决C#中HttpWebRequest、WebClient、HttpClient的使用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)