简体   繁体   中英

Calling REST Api using C#

Im calling a Rest API using C#. The URL is working from browser but when i call it from c# an exception is called

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll
A first chance exception of type 'System.Net.WebException' occurred in System.dll

This is my code

public static void getInputFromTeam1()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.150.1:8090/api/storeLayout/kinectToRacks/42");
            request.Method = "GET";
            request.Accept = "application/json";


            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream())
                {
                    if (webStream != null)
                    {
                        using (StreamReader responseReader = new StreamReader(webStream))
                        {
                            string response = responseReader.ReadToEnd();
                            Console.Out.WriteLine(response);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }

        }

Im new to C# and Rest Api. Please help me, I read many answers but none of them are working. Please help me thank you.

I would recommend you to have a look at the high-level WebClient -class instead. You must still pay close attention to the exception message.

        var serviceRequest = new WebClient();
        string response = serviceRequest.DownloadString(new Uri(url));

You can use this code.

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://192.168.150.1:8090/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = client.GetAsync("api/storeLayout/kinectToRacks/42").Result;
                if (response.IsSuccessStatusCode)
                {
                    var str = response.Content.ReadAsStringAsync();
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM