HttpAccess.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. public string GetString(string url, params HttpHeader[] headers)
  13. {
  14. var wc = new WebClient { Headers = { ["User-Agent"] = UserAgent } };
  15. wc.Proxy = new WebProxy();
  16. if (ProxyServer != null) wc.Proxy = new WebProxy(new Uri(ProxyServer));
  17. foreach (var header in headers) wc.Headers.Add(header.Name, header.Value);
  18. var str = wc.DownloadString(url);
  19. return str;
  20. }
  21. public string PutString(string url, string content, string contentType = "application/x-www-form-urlencoded;charset=UTF-8", params HttpHeader[] headers)
  22. {
  23. var wc = new WebClient { Headers = { ["User-Agent"] = UserAgent, ["Content-Type"] = contentType } };
  24. if (ProxyServer != null) wc.Proxy = new WebProxy(new Uri(ProxyServer));
  25. foreach (var header in headers) wc.Headers.Add(header.Name, header.Value);
  26. try
  27. {
  28. var str = wc.UploadString(url, "PUT", content);
  29. return str;
  30. }
  31. catch (WebException e)
  32. {
  33. if (e.Status == WebExceptionStatus.ProtocolError)
  34. {
  35. var str = Encoding.UTF8.GetString(e.Response.GetResponseStream().ToBytes());
  36. throw new WebException(str, e);
  37. }
  38. throw;
  39. }
  40. }
  41. public T GetJsonAnon<T>(T anon, string url, params HttpHeader[] headers)
  42. {
  43. return JsonConvert.DeserializeAnonymousType(GetString(url, headers), anon);
  44. }
  45. }
  46. }