[C#] 如何利用HttpWebRequest 叫用web API

在利用C# 叫用 Web API 時, 須要透過HttpWebRequest 去傳送request 和HttpWebResponse 去收return 回來的data. 以下是部份測試代碼.

            HttpWebRequest webRequest = HttpWebRequest.Create(TargetWebsite) as HttpWebRequest;

            webRequest.Method = "GET"; // "GET" / "POST"
            using (HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse)
            {
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream()))
                    {
                        string data = myStreamReader.ReadToEnd();
                        Console.WriteLine("data:" + data);
                    }
                }
            }

Reference

How to: Send Data Using the WebRequest Class, MSDN

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.