标签:
/// <summary> /// Post请求返回实体 /// </summary> /// <param name="url">请求地址</param> /// <param name="postData">请求数据</param> /// <returns>实体</returns> public static T PostResponse<T>(string url, object obj) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); string postData = JsonConvertTool.SerializeObject(obj); HttpContent httpContent = new StringContent(postData); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); T result = default(T); Task<HttpResponseMessage> taskResponse = httpClient.PostAsync(url, httpContent); taskResponse.Wait(); response = taskResponse.Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string s = reader.ReadToEnd(); result = JsonConvertTool.DeserializeObject<T>(s); } return result; } catch { return default(T); } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } }
/// <summary> /// 根据Url地址Get请求返回实体 /// </summary> /// <param name="url">请求的地址</param> /// <returns>实体</returns> public static T GetResponse<T>(string url) { HttpClient httpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }); HttpResponseMessage response = null; try { httpClient.MaxResponseContentBufferSize = 256000; httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"); httpClient.CancelPendingRequests(); httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); Task<HttpResponseMessage> taskResponse = httpClient.GetAsync(url); taskResponse.Wait(); T result = default(T); response = taskResponse.Result; if (response.IsSuccessStatusCode) { Task<System.IO.Stream> taskStream = response.Content.ReadAsStreamAsync(); taskStream.Wait(); System.IO.Stream dataStream = taskStream.Result; System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string s = reader.ReadToEnd(); result = JsonConvertTool.DeserializeObject<T>(s); } return result; } catch { return default(T); } finally { if (response != null) { response.Dispose(); } if (httpClient != null) { httpClient.Dispose(); } } }
HttpClient Post Get请求方法,留在以后可能会用到
标签:
原文地址:http://www.cnblogs.com/duanxy/p/5725216.html