Use httpclient in C#to access the REST API
Abnormal treatment problem
<code class="language-csharp"> private static void CreateObject() { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; // ... WebResponse webResponse = request.GetResponse(); // ... Console.WriteLine("对象创建成功。"); } catch (Exception e) { Console.WriteLine("-----------------"); Console.WriteLine(e.Message); } }</code>
The following example how to use the ASP.NET Web API client library:
<code class="language-csharp">using System; using System.Net.Http; using System.Net.Http.Headers; public static class Class1 { private const string URL = "https://sub.domain.com/objects.json"; private static string urlParameters = "?api_key=123"; public static void Main(string[] args) { // 创建HttpClient实例 using (HttpClient client = new HttpClient()) { // 设置API的基本地址 client.BaseAddress = new Uri(URL); // 为JSON格式添加Accept标头 client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // 发出GET请求 HttpResponseMessage response = client.GetAsync(urlParameters).Result; // 处理响应 if (response.IsSuccessStatusCode) { // 解析响应正文并执行任何必要的操作 } else { // 处理错误 } } } }</code>
The above is the detailed content of How to Efficiently Consume REST APIs in C# Using HttpClient?. For more information, please follow other related articles on the PHP Chinese website!