码迷,mamicode.com
首页 > Web开发 > 详细

Http Client请求调用接口

时间:2015-04-23 15:20:58      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

引用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();
        }

 

Http Client请求调用接口

标签:

原文地址:http://www.cnblogs.com/zxxblog/p/4450250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!