.NET處理HTTP請求


第一種:使用HttpWebRequest

string result = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);
            request.Method = "POST";
            request.ContentType = "application/json";
            string data = "{\n\"header\": {\n\"token\": \"30xxx6aaxxx93ac8cxx8668xx39xxxx\",\n\"username\": \"jdads\",\n\"password\": \"liuqiangdong2010\",\n\"action\": \"\"\n},\n\"body\": {}\n}";
            data = jsonData;
            byte[] byteData = Encoding.UTF8.GetBytes(data.ToString());
            request.ContentLength = byteData.Length;

            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    result = reader.ReadToEnd();
                    Console.WriteLine(result);

                }
            }
            

 


第二種:WebClient,也過時了:
第三種:HttpClient 當前主流用法,異步請求,自.NET4.5開始可從Nuget包管理中獲取。

 static async Task<Product> GetProductAsync(string path)
        {
            Product product = null;
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                product = await response.Content.ReadAsAsync<Product>();
            }
            return product;
        }

 

第四種:第三方類庫:

RestSharp

REST API請求測試類庫,可通過 NuGet 獲得。

Flurl.Http

最新的便捷的api測試工具,使用HttpClient實現,可通過 NuGet 安裝。

 

參考

Call a Web API From a .NET Client (C#)


免責聲明!

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



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