Response.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 ct = new ContentType(ContentType);
  21. if (ct.MediaType != "text/html")
  22. {
  23. html = null;
  24. return false;
  25. }
  26. using var stream = new MemoryStream(Body);
  27. var doc = new HtmlParser().ParseDocument(stream);
  28. html = doc;
  29. return true;
  30. }
  31. public HttpHeader[] GetServerTimeHeaders()
  32. {
  33. var lst = new List<HttpHeader>(2);
  34. var last = Headers?["last-modified"];
  35. var date = Headers?["date"];
  36. if (false == string.IsNullOrEmpty(last)) lst.Add(new HttpHeader("last-modified", last));
  37. if (false == string.IsNullOrEmpty(date)) lst.Add(new HttpHeader("date", date));
  38. return lst.ToArray();
  39. }
  40. public bool GetCss(out string css)
  41. {
  42. var ct = new ContentType(ContentType);
  43. if (ct.MediaType != "text/css")
  44. {
  45. css = null;
  46. return false;
  47. }
  48. var enc = Encoding.GetEncoding(ct.CharSet ?? "utf-8");
  49. css = enc.GetString(Body);
  50. return true;
  51. }
  52. public bool GetRedirect(out string redirectUrl)
  53. {
  54. if (false == StatusCode.In(HttpStatusCode.TemporaryRedirect, HttpStatusCode.Redirect, HttpStatusCode.Moved))
  55. {
  56. redirectUrl = null;
  57. return false;
  58. }
  59. redirectUrl = Headers["location"];
  60. return true;
  61. }
  62. }
  63. }