HttpBase.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using MediaBrowser.Model.Services;
  8. namespace SocketHttpListener
  9. {
  10. internal abstract class HttpBase
  11. {
  12. #region Private Fields
  13. private QueryParamCollection _headers;
  14. private Version _version;
  15. #endregion
  16. #region Internal Fields
  17. internal byte[] EntityBodyData;
  18. #endregion
  19. #region Protected Fields
  20. protected const string CrLf = "\r\n";
  21. #endregion
  22. #region Protected Constructors
  23. protected HttpBase(Version version, QueryParamCollection headers)
  24. {
  25. _version = version;
  26. _headers = headers;
  27. }
  28. #endregion
  29. #region Public Properties
  30. public string EntityBody
  31. {
  32. get
  33. {
  34. var data = EntityBodyData;
  35. return data != null && data.Length > 0
  36. ? getEncoding(_headers["Content-Type"]).GetString(data, 0, data.Length)
  37. : String.Empty;
  38. }
  39. }
  40. public QueryParamCollection Headers
  41. {
  42. get
  43. {
  44. return _headers;
  45. }
  46. }
  47. public Version ProtocolVersion
  48. {
  49. get
  50. {
  51. return _version;
  52. }
  53. }
  54. #endregion
  55. #region Private Methods
  56. private static Encoding getEncoding(string contentType)
  57. {
  58. if (contentType == null || contentType.Length == 0)
  59. return Encoding.UTF8;
  60. var i = contentType.IndexOf("charset=", StringComparison.Ordinal);
  61. if (i == -1)
  62. return Encoding.UTF8;
  63. var charset = contentType.Substring(i + 8);
  64. i = charset.IndexOf(';');
  65. if (i != -1)
  66. charset = charset.Substring(0, i).TrimEnd();
  67. return Encoding.GetEncoding(charset.Trim('"'));
  68. }
  69. #endregion
  70. #region Public Methods
  71. public byte[] ToByteArray()
  72. {
  73. return Encoding.UTF8.GetBytes(ToString());
  74. }
  75. #endregion
  76. }
  77. }