HttpAccess.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using D3NsCore.Models;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Net;
  5. using System.Text;
  6. namespace D3NsCore.Tools
  7. {
  8. internal class HttpAccess
  9. {
  10. private const string UserAgent = "DirectDDNS";
  11. public string ProxyServer { get; set; }
  12. static HttpAccess()
  13. {
  14. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
  15. }
  16. public string GetStringWithoutProxy(string url, params HttpHeader[] headers)
  17. {
  18. var wc = new WebClient { Headers = { ["User-Agent"] = UserAgent } };
  19. wc.Proxy = new WebProxy();
  20. foreach (var header in headers) wc.Headers.Add(header.Name, header.Value);
  21. var str = wc.DownloadString(url);
  22. return str;
  23. }
  24. public string GetString(string url, params HttpHeader[] headers)
  25. {
  26. var wc = new WebClient { Headers = { ["User-Agent"] = UserAgent } };
  27. wc.Proxy = new WebProxy();
  28. if (string.IsNullOrWhiteSpace(ProxyServer) == false) wc.Proxy = new WebProxy(new Uri(ProxyServer));
  29. foreach (var header in headers) wc.Headers.Add(header.Name, header.Value);
  30. var str = wc.DownloadString(url);
  31. return str;
  32. }
  33. public string PutString(string url, string content, string contentType = "application/x-www-form-urlencoded;charset=UTF-8", params HttpHeader[] headers)
  34. {
  35. var wc = new WebClient { Headers = { ["User-Agent"] = UserAgent, ["Content-Type"] = contentType } };
  36. if (string.IsNullOrWhiteSpace(ProxyServer)==false) wc.Proxy = new WebProxy(new Uri(ProxyServer));
  37. foreach (var header in headers) wc.Headers.Add(header.Name, header.Value);
  38. try
  39. {
  40. var str = wc.UploadString(url, "PUT", content);
  41. return str;
  42. }
  43. catch (WebException e)
  44. {
  45. if (e.Status == WebExceptionStatus.ProtocolError)
  46. {
  47. var str = Encoding.UTF8.GetString(e.Response.GetResponseStream().ToBytes());
  48. throw new WebException(str, e);
  49. }
  50. throw;
  51. }
  52. }
  53. public T GetJsonAnon<T>(T anon, string url, params HttpHeader[] headers)
  54. {
  55. return JsonConvert.DeserializeAnonymousType(GetString(url, headers), anon);
  56. }
  57. }
  58. }