HttpWebRequest:

命名空间: System.Net,这是.NET创建者最初开发用于使用HTTP请求的标准类。使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。HttpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。

  1. //POST方法
  2. public static string HttpPost(string Url, string postDataStr)
  3. {
  4. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  5. request.Method = "POST";
  6. request.ContentType = "application/x-www-form-urlencoded";
  7. Encoding encoding = Encoding.UTF8;
  8. byte[] postData = encoding.GetBytes(postDataStr);
  9. request.ContentLength = postData.Length;
  10. Stream myRequestStream = request.GetRequestStream();
  11. myRequestStream.Write(postData, 0, postData.Length);
  12. myRequestStream.Close();
  13. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  14. Stream myResponseStream = response.GetResponseStream();
  15. StreamReader myStreamReader = new StreamReader(myResponseStream, encoding);
  16. string retString = myStreamReader.ReadToEnd();
  17. myStreamReader.Close();
  18. myResponseStream.Close();
  19. return retString;
  20. }
  21. //GET方法
  22. public static string HttpGet(string Url, string postDataStr)
  23. {
  24. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
  25. request.Method = "GET";
  26. request.ContentType = "text/html;charset=UTF-8";
  27. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  28. Stream myResponseStream = response.GetResponseStream();
  29. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
  30. string retString = myStreamReader.ReadToEnd();
  31. myStreamReader.Close();
  32. myResponseStream.Close();
  33. return retString;
  34. }

WebClient:

命名空间System.Net,WebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。

  1. public class WebClientHelper
  2. {
  3. public static string DownloadString(string url)
  4. {
  5. WebClient wc = new WebClient();
  6. //wc.BaseAddress = url; //设置根目录
  7. wc.Encoding = Encoding.UTF8; //设置按照何种编码访问,如果不加此行,获取到的字符串中文将是乱码
  8. string str = wc.DownloadString(url);
  9. return str;
  10. }
  11. public static string DownloadStreamString(string url)
  12. {
  13. WebClient wc = new WebClient();
  14. 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");
  15. Stream objStream = wc.OpenRead(url);
  16. StreamReader _read = new StreamReader(objStream, Encoding.UTF8); //新建一个读取流,用指定的编码读取,此处是utf-8
  17. string str = _read.ReadToEnd();
  18. objStream.Close();
  19. _read.Close();
  20. return str;
  21. }
  22. public static void DownloadFile(string url, string filename)
  23. {
  24. WebClient wc = new WebClient();
  25. wc.DownloadFile(url, filename); //下载文件
  26. }
  27. public static void DownloadData(string url, string filename)
  28. {
  29. WebClient wc = new WebClient();
  30. byte [] bytes = wc.DownloadData(url); //下载到字节数组
  31. FileStream fs = new FileStream(filename, FileMode.Create);
  32. fs.Write(bytes, 0, bytes.Length);
  33. fs.Flush();
  34. fs.Close();
  35. }
  36. public static void DownloadFileAsync(string url, string filename)
  37. {
  38. WebClient wc = new WebClient();
  39. wc.DownloadFileCompleted += DownCompletedEventHandler;
  40. wc.DownloadFileAsync(new Uri(url), filename);
  41. Console.WriteLine("下载中。。。");
  42. }
  43. private static void DownCompletedEventHandler(object sender, AsyncCompletedEventArgs e)
  44. {
  45. Console.WriteLine(sender.ToString()); //触发事件的对象
  46. Console.WriteLine(e.UserState);
  47. Console.WriteLine(e.Cancelled);
  48. Console.WriteLine("异步下载完成!");
  49. }
  50. public static void DownloadFileAsync2(string url, string filename)
  51. {
  52. WebClient wc = new WebClient();
  53. wc.DownloadFileCompleted += (sender, e) =>
  54. {
  55. Console.WriteLine("下载完成!");
  56. Console.WriteLine(sender.ToString());
  57. Console.WriteLine(e.UserState);
  58. Console.WriteLine(e.Cancelled);
  59. };
  60. wc.DownloadFileAsync(new Uri(url), filename);
  61. Console.WriteLine("下载中。。。");
  62. }
  63. }

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

  1. public class Singleton {
  2. private static Singleton instance = null;
  3. private Singleton (){}
  4. public static Singleton getInstance() {
  5. if (instance == null) {
  6. instance = new Singleton();
  7. }
  8. return instance;
  9. }
  10. }

这种方式是最基本的实现方式,这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,所以严格意义上它并不算单例模式。
这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。
饿汉模式: 类初始化时,会立即加载该对象,线程天生安全,调用效率高

  1. public class Singleton {
  2. private static Singleton instance = new Singleton();
  3. private Singleton (){}
  4. public static Singleton getInstance() {
  5. return instance;
  6. }
  7. }

双检锁/双重校验锁(DCL,即 double-checked locking):这种方式采用双锁机制,安全且在多线程情况下能保持高性能

  1. public class Singleton {
  2. private volatile static Singleton singleton;
  3. private Singleton (){}
  4. public static Singleton getSingleton() {
  5. if (singleton == null) {
  6. synchronized (Singleton.class) {
  7. if (singleton == null) {
  8. singleton = new Singleton();
  9. }
  10. }
  11. }
  12. return singleton;
  13. }
  14. }

HttpClient:

  1. public class HttpClientHelper
  2. {
  3. private static readonly object LockObj = new object();
  4. private static HttpClient client = null;
  5. public HttpClientHelper() {
  6. GetInstance();
  7. }
  8. public static HttpClient GetInstance()
  9. {
  10. if (client == null)
  11. {
  12. lock (LockObj)
  13. {
  14. if (client == null)
  15. {
  16. client = new HttpClient();
  17. }
  18. }
  19. }
  20. return client;
  21. }
  22. public async Task<string> PostAsync(string url, string strJson)//post异步请求方法
  23. {
  24. try
  25. {
  26. HttpContent content = new StringContent(strJson);
  27. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
  28. //由HttpClient发出异步Post请求
  29. HttpResponseMessage res = await client.PostAsync(url, content);
  30. if (res.StatusCode == System.Net.HttpStatusCode.OK)
  31. {
  32. string str = res.Content.ReadAsStringAsync().Result;
  33. return str;
  34. }
  35. else
  36. return null;
  37. }
  38. catch (Exception ex)
  39. {
  40. return null;
  41. }
  42. }
  43. public string Post(string url, string strJson)//post同步请求方法
  44. {
  45. try
  46. {
  47. HttpContent content = new StringContent(strJson);
  48. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
  49. //client.DefaultRequestHeaders.Connection.Add("keep-alive");
  50. //由HttpClient发出Post请求
  51. Task<HttpResponseMessage> res = client.PostAsync(url, content);
  52. if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
  53. {
  54. string str = res.Result.Content.ReadAsStringAsync().Result;
  55. return str;
  56. }
  57. else
  58. return null;
  59. }
  60. catch (Exception ex)
  61. {
  62. return null;
  63. }
  64. }
  65. public string Get(string url)
  66. {
  67. try
  68. {
  69. var responseString = client.GetStringAsync(url);
  70. return responseString.Result;
  71. }
  72. catch (Exception ex)
  73. {
  74. return null;
  75. }
  76. }
  77. }

HttpClient有预热机制,第一次请求比较慢;可以通过初始化前发送一次head请求解决:

  1. _httpClient = new HttpClient() { BaseAddress = new Uri(BASE_ADDRESS) };
  2. //帮HttpClient热身
  3. _httpClient.SendAsync(new HttpRequestMessage {
  4. Method = new HttpMethod("HEAD"),
  5. RequestUri = new Uri(BASE_ADDRESS + "/") })
  6. .Result.EnsureSuccessStatusCode();

三者区别列表:
image.png