Response.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using AngleSharp.Html.Dom;
  2. using AngleSharp.Html.Parser;
  3. using Rac.Tools;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Mime;
  8. using System.Text;
  9. namespace Rac.Models
  10. {
  11. internal class Response
  12. {
  13. public HttpStatusCode StatusCode { get; set; }
  14. public string StatusDescription { get; set; }
  15. public WebHeaderCollection Headers { get; set; }
  16. public byte[] Body { get; set; }
  17. public string ContentType => Headers?["content-type"];
  18. public bool GetHtmlDocument(out IHtmlDocument html)
  19. {
  20. var contentType = ContentType;
  21. if (null == contentType)
  22. {
  23. html = null;
  24. return false;
  25. }
  26. var ct = new ContentType(contentType);
  27. if (ct.MediaType != "text/html")
  28. {
  29. html = null;
  30. return false;
  31. }
  32. using var stream = new MemoryStream(Body);
  33. var doc = new HtmlParser().ParseDocument(stream);
  34. html = doc;
  35. return true;
  36. }
  37. public HttpHeader[] GetServerTimeHeaders()
  38. {
  39. var lst = new List<HttpHeader>(2);
  40. var last = Headers?["last-modified"];
  41. var date = Headers?["date"];
  42. if (false == string.IsNullOrEmpty(last)) lst.Add(new HttpHeader("last-modified", last));
  43. if (false == string.IsNullOrEmpty(date)) lst.Add(new HttpHeader("date", date));
  44. return lst.ToArray();
  45. }
  46. public bool GetCss(out string css)
  47. {
  48. var contentType = ContentType;
  49. if (null == contentType)
  50. {
  51. css = null;
  52. return false;
  53. }
  54. var ct = new ContentType(contentType);
  55. if (ct.MediaType != "text/css")
  56. {
  57. css = null;
  58. return false;
  59. }
  60. var enc = Encoding.GetEncoding(ct.CharSet ?? "utf-8");
  61. css = enc.GetString(Body);
  62. return true;
  63. }
  64. public bool GetRedirect(out string redirectUrl)
  65. {
  66. if (false == StatusCode.In(HttpStatusCode.TemporaryRedirect, HttpStatusCode.Redirect, HttpStatusCode.Moved))
  67. {
  68. redirectUrl = null;
  69. return false;
  70. }
  71. redirectUrl = Headers["location"];
  72. return true;
  73. }
  74. }
  75. }