This is the code I have so far:
public class Class1 { private const string URL = "https://sub.domain.com/objects.json?api_key=123"; private const string DATA = @"{""object"":{""name"":""Name""}}"; static void Main(string[] args) { Class1.CreateObject(); } private static void CreateObject() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); requestWriter.Write(DATA); requestWriter.Close(); try { WebResponse webResponse = request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); Console.Out.WriteLine(response); responseReader.Close(); } catch (Exception e) { Console.Out.WriteLine("-----------------"); Console.Out.WriteLine(e.Message); } } }
The problem is that I think the exception block is being triggered (because when I remove the try-catch, I get a server error (500) message. But I don't see the Console.Out lines I put in the catch block.
My Console:
The thread 'vshost.NotifyLoad' (0x1a20) has exited with code 0 (0x0). The thread '<No Name>' (0x1988) has exited with code 0 (0x0). The thread 'vshost.LoadReference' (0x1710) has exited with code 0 (0x0). 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'c:\users\l. preston sego iii\documents\visual studio 11\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe', Symbols loaded. 'ConsoleApplication1.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. A first chance exception of type 'System.Net.WebException' occurred in System.dll The thread 'vshost.RunParkingWindow' (0x184c) has exited with code 0 (0x0). The thread '<No Name>' (0x1810) has exited with code 0 (0x0). The program '[2780] ConsoleApplication1.vshost.exe: Program Trace' has exited with code 0 (0x0). The program '[2780] ConsoleApplication1.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
Applications call C API functions defined in C language header files, and a dynamic link library (DLL). Each function call returns an integer result code, defined in the ctgstdat. h header file. A function that completes normally returns the code CTG_STAT_OK .
What is REST. REST is the acronym that stands for: Representational State Transfer. REST is an architectural style of distributed system. It is based upon the set of principles that describes how network resources are defined and addressed. These set of principles was first described by “Roy Fielding” in 2000.
The ASP.NET Web API has replaced the WCF Web API previously mentioned.
I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".
Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.
Here's how your example would look when implemented using the ASP.NET Web API Client Library:
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; namespace ConsoleProgram { public class DataObject { public string Name { get; set; } } public class Class1 { private const string URL = "https://sub.domain.com/objects.json"; private string urlParameters = "?api_key=123"; static void Main(string[] args) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) { // Parse the response body. var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll foreach (var d in dataObjects) { Console.WriteLine("{0}", d.Name); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); } // Make any other calls using HttpClient here. // Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous. client.Dispose(); } } }
If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?
For more details, including other examples, see Call a Web API From a .NET Client (C#)
This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services
My suggestion would be to use RestSharp. You can make calls to REST services and have them cast into POCO objects with very little boilerplate code to actually have to parse through the response. This will not solve your particular error, but it answers your overall question of how to make calls to REST services. Having to change your code to use it should pay off in the ease of use and robustness moving forward. That is just my two cents though.
Example:
namespace RestSharpThingy { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using RestSharp; public static class Program { public static void Main() { Uri baseUrl = new Uri("https://httpbin.org/"); IRestClient client = new RestClient(baseUrl); IRestRequest request = new RestRequest("get", Method.GET) { Credentials = new NetworkCredential("testUser", "P455w0rd") }; request.AddHeader("Authorization", "Bearer qaPmk9Vw8o7r7UOiX-3b-8Z_6r3w0Iu2pecwJ3x7CngjPp2fN3c61Q_5VU3y0rc-vPpkTKuaOI2eRs3bMyA5ucKKzY1thMFoM0wjnReEYeMGyq3JfZ-OIko1if3NmIj79ZSpNotLL2734ts2jGBjw8-uUgKet7jQAaq-qf5aIDwzUo0bnGosEj_UkFxiJKXPPlF2L4iNJSlBqRYrhw08RK1SzB4tf18Airb80WVy1Kewx2NGq5zCC-SCzvJW-mlOtjIDBAQ5intqaRkwRaSyjJ_MagxJF_CLc4BNUYC3hC2ejQDoTE6HYMWMcg0mbyWghMFpOw3gqyfAGjr6LPJcIly__aJ5__iyt-BTkOnMpDAZLTjzx4qDHMPWeND-TlzKWXjVb5yMv5Q6Jg6UmETWbuxyTdvGTJFzanUg1HWzPr7gSs6GLEv9VDTMiC8a5sNcGyLcHBIJo8mErrZrIssHvbT8ZUPWtyJaujKvdgazqsrad9CO3iRsZWQJ3lpvdQwucCsyjoRVoj_mXYhz3JK3wfOjLff16Gy1NLbj4gmOhBBRb8rJnUXnP7rBHs00FAk59BIpKLIPIyMgYBApDCut8V55AgXtGs4MgFFiJKbuaKxq8cdMYEVBTzDJ-S1IR5d6eiTGusD5aFlUkAs9NV_nFw"); request.AddParameter("clientId", 123); IRestResponse<RootObject> response = client.Execute<RootObject>(request); if (response.IsSuccessful) { response.Data.Write(); } else { Console.WriteLine(response.ErrorMessage); } Console.WriteLine(); string path = Assembly.GetExecutingAssembly().Location; string name = Path.GetFileName(path); request = new RestRequest("post", Method.POST); request.AddFile(name, File.ReadAllBytes(path), name, "application/octet-stream"); response = client.Execute<RootObject>(request); if (response.IsSuccessful) { response.Data.Write(); } else { Console.WriteLine(response.ErrorMessage); } Console.ReadLine(); } private static void Write(this RootObject rootObject) { Console.WriteLine("clientId: " + rootObject.args.clientId); Console.WriteLine("Accept: " + rootObject.headers.Accept); Console.WriteLine("AcceptEncoding: " + rootObject.headers.AcceptEncoding); Console.WriteLine("AcceptLanguage: " + rootObject.headers.AcceptLanguage); Console.WriteLine("Authorization: " + rootObject.headers.Authorization); Console.WriteLine("Connection: " + rootObject.headers.Connection); Console.WriteLine("Dnt: " + rootObject.headers.Dnt); Console.WriteLine("Host: " + rootObject.headers.Host); Console.WriteLine("Origin: " + rootObject.headers.Origin); Console.WriteLine("Referer: " + rootObject.headers.Referer); Console.WriteLine("UserAgent: " + rootObject.headers.UserAgent); Console.WriteLine("origin: " + rootObject.origin); Console.WriteLine("url: " + rootObject.url); Console.WriteLine("data: " + rootObject.data); Console.WriteLine("files: "); foreach (KeyValuePair<string, string> kvp in rootObject.files ?? Enumerable.Empty<KeyValuePair<string, string>>()) { Console.WriteLine("\t" + kvp.Key + ": " + kvp.Value); } } } public class Args { public string clientId { get; set; } } public class Headers { public string Accept { get; set; } public string AcceptEncoding { get; set; } public string AcceptLanguage { get; set; } public string Authorization { get; set; } public string Connection { get; set; } public string Dnt { get; set; } public string Host { get; set; } public string Origin { get; set; } public string Referer { get; set; } public string UserAgent { get; set; } } public class RootObject { public Args args { get; set; } public Headers headers { get; set; } public string origin { get; set; } public string url { get; set; } public string data { get; set; } public Dictionary<string, string> files { get; set; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With