C# Http請求接口數據的兩種方式Get and Post

面向接口編程是一種設計思想,不管用什麼語言都少不了面向接口開發思想,在軟件開發過程當中,經常要調用接口,接下來就是介紹C#調用其它開發商提供的接口進行獲取數據,http接口方式獲取接口數據。編程

Get請求數據:json

 using (var httpClient = new HttpClient())
            {                
                //get
                var url = new Uri("接口網絡地址");
                // response
                var response = httpClient.GetAsync(url).Result;
                var data = response.Content.ReadAsStringAsync().Result;
               return data;//接口調用成功獲取的數據
            }

Post請求數據:網絡

using (var httpClient = new HttpClient())
            {             
                //post
                var url = new Uri("接口網絡地址");
                var body = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "參數1", "值1"},
                    { "參數2", "值2"},
                    { "參數3", "值3"},
                    { "參數4", "值4"},
                });
                // response
                var response = httpClient.PostAsync(url, body).Result;  
                var data = response.Content.ReadAsStringAsync().Result;
                return data;//接口調用成功數據
            }

  若是接口調用須要傳請求頭可使用以下代碼設置請求頭:app

 httpClient.DefaultRequestHeaders.Add("Accept", "application/json");//設置請求頭
相關文章
相關標籤/搜索