HTTPUrlEncodedForm.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace BestHTTP.Forms
  6. {
  7. /// <summary>
  8. /// A HTTP Form implementation to send textual values.
  9. /// </summary>
  10. public sealed class HTTPUrlEncodedForm : HTTPFormBase
  11. {
  12. private const int EscapeTreshold = 256;
  13. private byte[] CachedData;
  14. public override void PrepareRequest(HTTPRequest request)
  15. {
  16. request.SetHeader("Content-Type", "application/x-www-form-urlencoded");
  17. }
  18. public override byte[] GetData()
  19. {
  20. if (CachedData != null && !IsChanged)
  21. return CachedData;
  22. StringBuilder sb = new StringBuilder();
  23. // Create a "field1=value1&field2=value2" formatted string
  24. for (int i = 0; i < Fields.Count; ++i)
  25. {
  26. var field = Fields[i];
  27. if (i > 0)
  28. sb.Append("&");
  29. sb.Append(EscapeString(field.Name));
  30. sb.Append("=");
  31. if (!string.IsNullOrEmpty(field.Text) || field.Binary == null)
  32. sb.Append(EscapeString(field.Text));
  33. else
  34. // If forced to this form type with binary data, we will create a string from the binary data first and encode this string.
  35. sb.Append(EscapeString(Encoding.UTF8.GetString(field.Binary, 0, field.Binary.Length)));
  36. }
  37. IsChanged = false;
  38. return CachedData = Encoding.UTF8.GetBytes(sb.ToString());
  39. }
  40. public static string EscapeString(string originalString)
  41. {
  42. if (originalString.Length < EscapeTreshold)
  43. return Uri.EscapeDataString(originalString);
  44. else
  45. {
  46. int loops = originalString.Length / EscapeTreshold;
  47. StringBuilder sb = new StringBuilder(loops);
  48. for (int i = 0; i <= loops; i++)
  49. sb.Append(i < loops ?
  50. Uri.EscapeDataString(originalString.Substring(EscapeTreshold * i, EscapeTreshold)) :
  51. Uri.EscapeDataString(originalString.Substring(EscapeTreshold * i)));
  52. return sb.ToString();
  53. }
  54. }
  55. }
  56. }