C#发送POST,GET,DELETE请求API,并接受返回值

发送POST请求

        /// <summary>
        /// API发送POST请求
        /// </summary>
        /// <param name="url">请求的API地址</param>
        /// <param name="parametersJson">POST过去的参数(JSON格式)字符串</param>
        /// <returns></returns>
        public static string ApiPost(string url, string parametersJson)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiHttp"]);
            // 为JSON格式添加一个Accept报头
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //需要传递的参数(参数封装成JSON)
            HttpContent content = new StringContent(parametersJson)
            {
                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
            };

            HttpResponseMessage response = client.PostAsync(url, content).Result;
            response.EnsureSuccessStatusCode();
            return response.Content.ReadAsStringAsync().Result;
        } 

 

发送GET请求

        /// <summary>
        /// API发送GET请求,返回Json
        /// </summary>
        /// <param name="url"></param>
        /// <returns>如果未成功返回空</returns>
        public static string ApiGet(string url)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiHttp"]);
            // 为JSON格式添加一个Accept报头
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
            return "";
        } 

 

发送DELETE请求

        /// <summary>
        ///  API发送DELETE请求,返回状态:200成功,201失败
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string ApiDelete(string url)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiHttp"]);
            // 为JSON格式添加一个Accept报头
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
            return "";
        }

 

来源:中国建筑市场网

posted @ 2016-03-01 16:01  苦逼的猿人  阅读(3152)  评论(0编辑  收藏  举报