Program.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. namespace ApiSnippet
  8. {
  9. class Program
  10. {
  11. static string GetSignature(string parameters, string secret)
  12. {
  13. string[] unsorted = parameters.Split('&');
  14. List<string> sorted = new List<string>();
  15. string sortedParams = "";
  16. //Removing unwanted parameters
  17. for (int i = 0; i < unsorted.Length; i++)
  18. {
  19. if (!unsorted[i].Contains("="))
  20. {
  21. continue;
  22. }
  23. string[] keyVal = unsorted[i].Split('=');
  24. if (keyVal[0].Equals("sign") || keyVal[1].Length == 0)
  25. {
  26. continue;
  27. }
  28. sorted.Add(unsorted[i]);
  29. }
  30. if (sorted.Count == 0)
  31. {
  32. return null;
  33. }
  34. //Sorting the remaining parameters
  35. sorted.Sort();
  36. //Building the sorted parameters string
  37. for (int i = 0; i < sorted.Count; i++)
  38. {
  39. if (i < sorted.Count - 1)
  40. {
  41. sorted[i] += '&';
  42. }
  43. sortedParams += sorted[i];
  44. }
  45. sortedParams += secret;
  46. //Encoding
  47. byte[] encodedPassword = new UTF8Encoding().GetBytes(sortedParams);
  48. byte[] hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
  49. string encoded = BitConverter.ToString(hash).Replace("-", String.Empty).ToLower();
  50. return encoded;
  51. }
  52. public void Main(string[] args)
  53. {
  54. //version (版本号, v1代表7天, v6代表1天) 接口参数 cityid (城市编号), city (城市名称如:青岛), ip (ip地址, 默认当前ip天气)
  55. string parameters = "version=v1";
  56. string url = String.Concat("https://www.tianqiapi.com/api/?", parameters);
  57. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  58. request.Method = "GET";
  59. request.Timeout = 5000;
  60. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  61. string jsonString;
  62. using (Stream stream = response.GetResponseStream())
  63. {
  64. StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
  65. jsonString = reader.ReadToEnd();
  66. }
  67. //Response
  68. Console.WriteLine(jsonString);
  69. }
  70. }
  71. }