Http Client请求调用接口
引用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();
//用完要记得释放
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。