1 public class HttpClientHelper<T> 2 { 3 /// <summary> 4 /// Get请求 返回实体 5 /// </summary> 6 /// <param name="url"></param> 7 /// <param name="t"></param> 8 /// <returns></returns> 9 public static T Get(string url, T t) 10 { 11 HttpClient client = new HttpClient(); 12 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 13 var result = client.GetAsync(url).Result; 14 if (result.IsSuccessStatusCode) 15 { 16 string re = result.Content.ReadAsStringAsync().Result; 17 var jo = JObject.Parse(re); 18 JSchema schema = JSchema.Parse(JsonConvert.SerializeObject(t)); 19 if (jo.IsValid(schema)) 20 { 21 var m = JsonConvert.DeserializeObject<T>(re); 22 return m; 23 } 24 else 25 { 26 return default(T); 27 } 28 } 29 else 30 { 31 return default(T); 32 } 33 } 34 35 /// <summary> 36 /// Get请求 返回string 37 /// </summary> 38 /// <param name="url"></param> 39 /// <param name="t"></param> 40 /// <returns></returns> 41 public static string Get(string url) 42 { 43 HttpClient client = new HttpClient(); 44 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 45 var result = client.GetAsync(url).Result; 46 if (result.IsSuccessStatusCode) 47 { 48 string re = result.Content.ReadAsStringAsync().Result; 49 return re; 50 } 51 else 52 { 53 return ""; 54 } 55 } 56 57 /// <summary> 58 /// Post请求 返回实体 59 /// </summary> 60 /// <param name="url"></param> 61 /// <param name="t"></param> 62 /// <returns></returns> 63 public static T Post(string url, T t, string json = null) 64 { 65 var client = new HttpClient(); 66 67 var postContent = new StringContent(json, UTF8Encoding.UTF8, "application/json"); 68 var result = client.PostAsync(url, postContent).Result; 69 if (result.IsSuccessStatusCode) 70 { 71 string re = result.Content.ReadAsStringAsync().Result; 72 var jo = JObject.Parse(re); 73 JSchema schema = JSchema.Parse(JsonConvert.SerializeObject(t)); 74 if (jo.IsValid(schema)) 75 { 76 var m = JsonConvert.DeserializeObject<T>(re); 77 return m; 78 } 79 else 80 { 81 return default(T); 82 } 83 } 84 return default(T); 85 } 86 87 /// <summary> 88 /// Post请求 返回string 89 /// </summary> 90 /// <param name="url"></param> 91 /// <param name="t"></param> 92 /// <returns></returns> 93 public static string Post(string url, string json =null) 94 { 95 var client = new HttpClient(); 96 var postContent = new StringContent(json, UTF8Encoding.UTF8, "application/json"); 97 var result = client.PostAsync(url, postContent).Result; 98 if (result.IsSuccessStatusCode) 99 { 100 return result.Content.ReadAsStringAsync().Result; 101 } 102 return null; 103 } 104 105 }
原文:https://www.cnblogs.com/LmuQuan/p/11233702.html