TapHttpUtils.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System.Linq;
  2. using System.Text;
  3. using System.Collections.Specialized;
  4. using System.Net.Http;
  5. using UnityEngine;
  6. using TapSDK.Core.Internal.Log;
  7. namespace TapSDK.Core.Internal.Http {
  8. public class TapHttpUtils {
  9. public static void PrintRequest(HttpClient client, HttpRequestMessage request, string content = null) {
  10. if (TapLogger.LogDelegate == null) {
  11. return;
  12. }
  13. if (client == null) {
  14. return;
  15. }
  16. if (request == null) {
  17. return;
  18. }
  19. StringBuilder sb = new StringBuilder();
  20. sb.AppendLine("=== HTTP Request Start ===");
  21. sb.AppendLine($"URL: {request.RequestUri}");
  22. sb.AppendLine($"Method: {request.Method}");
  23. sb.AppendLine($"Headers: ");
  24. foreach (var header in client.DefaultRequestHeaders) {
  25. sb.AppendLine($"\t{header.Key}: {string.Join(",", header.Value.ToArray())}");
  26. }
  27. foreach (var header in request.Headers) {
  28. sb.AppendLine($"\t{header.Key}: {string.Join(",", header.Value.ToArray())}");
  29. }
  30. if (request.Content != null) {
  31. foreach (var header in request.Content.Headers) {
  32. sb.AppendLine($"\t{header.Key}: {string.Join(",", header.Value.ToArray())}");
  33. }
  34. }
  35. if (!string.IsNullOrEmpty(content)) {
  36. sb.AppendLine($"Content: {content}");
  37. }
  38. sb.AppendLine("=== HTTP Request End ===");
  39. TapLog.Log(sb.ToString());
  40. }
  41. public static void PrintResponse(HttpResponseMessage response, string content = null) {
  42. if (TapLogger.LogDelegate == null) {
  43. return;
  44. }
  45. StringBuilder sb = new StringBuilder();
  46. sb.AppendLine("=== HTTP Response Start ===");
  47. sb.AppendLine($"URL: {response.RequestMessage.RequestUri}");
  48. sb.AppendLine($"Status Code: {response.StatusCode}");
  49. if (!string.IsNullOrEmpty(content)) {
  50. sb.AppendLine($"Content: {content}");
  51. }
  52. sb.AppendLine("=== HTTP Response End ===");
  53. TapLog.Log(sb.ToString());
  54. }
  55. public static NameValueCollection ParseQueryString(string queryString)
  56. {
  57. if (string.IsNullOrEmpty(queryString)) {
  58. return null;
  59. }
  60. if (queryString.Length > 0 && queryString[0] == '?') {
  61. queryString = queryString.Substring(1);
  62. }
  63. NameValueCollection queryParameters = new NameValueCollection();
  64. string[] querySegments = queryString.Split('&');
  65. foreach(string segment in querySegments)
  66. {
  67. string[] parts = segment.Split('=');
  68. if (parts.Length > 0)
  69. {
  70. string key = parts[0].Trim(new char[] { '?', ' ' });
  71. string val = parts[1].Trim();
  72. queryParameters.Add(key, val);
  73. }
  74. }
  75. return queryParameters;
  76. }
  77. }
  78. }