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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM