HttpUtils.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. namespace FastReport.Cloud
  6. {
  7. /// <summary>
  8. /// Static class that contains HTTP utilities.
  9. /// </summary>
  10. internal static class HttpUtils
  11. {
  12. #region Public Methods
  13. /// <summary>
  14. /// Encodes the URL string.
  15. /// </summary>
  16. /// <param name="str">The URL string.</param>
  17. /// <returns>The encoded URL string.</returns>
  18. public static string UrlEncode(string str)
  19. {
  20. StringBuilder sb = new StringBuilder();
  21. StringReader reader = new StringReader(str);
  22. int charCode = reader.Read();
  23. while (charCode != -1)
  24. {
  25. if (((charCode >= 48) && (charCode <= 57)) || ((charCode >= 65) && (charCode <= 90)) || ((charCode >= 97) && (charCode <= 122)))
  26. {
  27. sb.Append((char)charCode);
  28. }
  29. else if (charCode == 32)
  30. {
  31. sb.Append("+");
  32. }
  33. else
  34. {
  35. sb.AppendFormat("%{0:x2}", charCode);
  36. }
  37. charCode = reader.Read();
  38. }
  39. return sb.ToString();
  40. }
  41. /// <summary>
  42. /// Encodes the dictionary with URL parameters.
  43. /// </summary>
  44. /// <param name="data">The dictionary with parameters.</param>
  45. /// <returns>The encoded string.</returns>
  46. public static string UrlDataEncode(Dictionary<string, string> data)
  47. {
  48. StringBuilder sb = new StringBuilder();
  49. string format = "{0}={1}";
  50. bool first = true;
  51. foreach (KeyValuePair<string, string> pair in data)
  52. {
  53. sb.AppendFormat(format, pair.Key, pair.Value);
  54. if (first)
  55. {
  56. format = "&{0}={1}";
  57. first = false;
  58. }
  59. }
  60. return sb.ToString();
  61. }
  62. /// <summary>
  63. /// Decodes the URL string.
  64. /// </summary>
  65. /// <param name="str">The URL string.</param>
  66. /// <returns>The decoded URL string.</returns>
  67. public static string UrlDecode(string str)
  68. {
  69. return Uri.UnescapeDataString(str);
  70. }
  71. #endregion // Public Methods
  72. }
  73. }