In this post we will discuss how to send web request to URL for getting data. It will be a GET request. I know in daily development practices we need this sample code. Please check below, I hope it will help you.

 In below code sample we will use “WebRequest” method to make the web request.

                var url = “https://Abc.com”
                //sending web requst to URL for getting data.
                var request = WebRequest.Create(url);
                request.Method = "GET";
                var data = "";
                using (var webResponse = request.GetResponse())
                {
                    using (var webStream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(webStream))
                        {
                            data = reader.ReadToEnd();
                        }
                    }
                }

In below code sample we will use “HttpClient” to make the web request

          HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://abc.com/");
            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("api/Values").Result;    // controller url
            if (response.IsSuccessStatusCode)
           {
              var responseaData = response.Content.ReadAsStringAsync().Result;
           }
            else
            {
             String msg= response.StatusCode + " " +response.ReasonPhrase);
            }

For more such topics you can Search or Visit our C# Section , IIS Section & SQL Section too.

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore More

Working With File Class In C#

In C#, ‘File’ class provides many static methods for moving, copying, and deleting files. These Static methods involve moving a file and copying and deleting a file also. Let’s check

How to Read a Text File in C#

In C# ‘File’ class provides static methods to read given text file data. The File.ReadAllText() method opens a text file, reads all the text present in the file into a

C# | How to use Interface references

In C#, you’re permitted to make a reference variable of an interface type or in other words, you’re permitted to form an interface reference variable. Such kind of variable can