引用Nettonsoft.Json
引用System.Net.Http
/// <summary> /// Http Client请求 /// </summary> /// <param name="url">api地址</param> /// <param name="dic">参数,这里用的是json格式</param> /// <returns></returns> public string CallApiByHttpClient<T>(string url, T param) { string result = ""; HttpClient httpClient = new HttpClient(); 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"); var requestJson = JsonConvert.SerializeObject(param); HttpContent httpContent = new StringContent(requestJson); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); result = httpClient.PostAsync(url, httpContent) .Result.Content.ReadAsStringAsync().Result;//post请求 //result = httpClient.GetAsync(url).Result.Content.ReadAsStringAsync().Result;//get请求 //用完要记得释放
httpClient.Dispose();
}
时间: 2024-10-27 07:31:29