How to send web request to URL for getting data

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 *