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 "";
        }

 

转载于:https://www.cnblogs.com/lb809663396/p/5231372.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值