C# 接口工具类

293 阅读3分钟

一、同步接口工具类

using System;
using System.Net;

namespace YourNamespace
{
    public static class WebApiClient
    {
        public static string SendPostRequest(string url, string requestBody)
        {
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json;charset=utf-8");
            client.Headers.Add("User-Agent", "YourUserAgent/1.0");

            string responseData;
            
            try
            {
                responseData = client.UploadString(url, "POST", requestBody);
            }
            catch (WebException ex)
            {
                // Handle any exception that occurred during the request
                // For example, you can log the exception or throw a custom exception
                // based on your business requirements
                // Here, we are re-throwing the exception
                throw ex;
            }
            
            return responseData;
        }
    }
}

二、异步接口工具类

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace YourNamespace
{
    public static class WebApiClient
    {
        public static async Task<string> SendPostRequestAsync(string url, string requestBody)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("User-Agent", "YourUserAgent/1.0");
                
                StringContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                
                HttpResponseMessage response = await client.PostAsync(url, content);
                
                string responseData = await response.Content.ReadAsStringAsync();
                
                return responseData;
            }
        }
    }
}

当涉及到 HttpClient 类的使用时,以下是一个使用手册的示例,涵盖了常见的用法和操作:

HttpClient 使用手册

1. 创建 HttpClient 实例

使用 using 块创建和管理 HttpClient 实例,确保及时释放资源。

using System;
using System.Net.Http;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            using (HttpClient client = new HttpClient())
            {
                // HttpClient 实例的操作
            }

            // 在这之后,HttpClient 实例已被释放,不再可用
        }
    }
}

2. 发送 GET 请求

使用 GetAsync 方法发送 GET 请求,并处理响应。

using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = await client.GetAsync("https://api.example.com/users");
    
    if (response.IsSuccessStatusCode)
    {
        string responseBody = await response.Content.ReadAsStringAsync();
        // 处理响应内容
    }
    else
    {
        // 处理请求失败的情况
        Console.WriteLine($"请求失败: {response.StatusCode}");
    }
}

3. 发送 POST 请求

使用 PostAsync 方法发送 POST 请求,并处理响应。

using (HttpClient client = new HttpClient())
{
    string requestBody = "{\"name\": \"John\", \"email\": \"john@example.com\"}";
    
    HttpContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync("https://api.example.com/users", content);
    
    if (response.IsSuccessStatusCode)
    {
        string responseBody = await response.Content.ReadAsStringAsync();
        // 处理响应内容
    }
    else
    {
        // 处理请求失败的情况
        Console.WriteLine($"请求失败: {response.StatusCode}");
    }
}

4. 发送带请求头的请求

使用 DefaultRequestHeaders 属性添加请求头,并发送请求。

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("User-Agent", "YourUserAgent/1.0");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YourToken");
    
    // 发送请求...
}

5. 异步操作

使用异步方法进行 HTTP 请求,以充分利用系统资源。

using (HttpClient client = new HttpClient())
{
    // 异步发送 GET 请求
    HttpResponseMessage response = await client.GetAsync("https://api.example.com/users");
    
    // 异步发送 POST 请求
    string requestBody = "{\"name\": \"John\", \"email\": \"john@example.com\"}";
    HttpContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");
    HttpResponseMessage response = await client.PostAsync("https://api.example.com/users", content);
    
    // 其他异步操作...
}

6. 释放资源

在使用完 HttpClient 后,确保调用 Dispose() 方法释放资源。

using (HttpClient client = new HttpClient())
{
    // HttpClient 实例的操作
}

// 在这之后,HttpClient 实例已被释放,不再可用

以上是关于使用 HttpClient 类的一些常见操作和用法的简要手册。根据你的具体需求,可以进一步深入了解 HttpClient 类的更多功能和方法,以及相关的最佳实践。

当涉及到基于 HttpClient 进行封装的工具类时,可以创建一个通用的HTTP 客户端类,它提供了常见的发送 HTTP 请求的方法,并具备可扩展性和灵活性。以下是一个完善的基于 HttpClient 的工具类示例:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace YourNamespace
{
    public class HttpClientHelper : IDisposable
    {
        private readonly HttpClient _client;

        public HttpClientHelper()
        {
            _client = new HttpClient();
        }

        public void SetBaseUrl(string baseUrl)
        {
            _client.BaseAddress = new Uri(baseUrl);
        }

        public void SetRequestHeader(string headerName, string headerValue)
        {
            _client.DefaultRequestHeaders.Add(headerName, headerValue);
        }

        public void SetBearerToken(string token)
        {
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }

        public async Task<string> SendGetRequestAsync(string url)
        {
            HttpResponseMessage response = await _client.GetAsync(url);
            return await HandleResponseAsync(response);
        }

        public async Task<string> SendPostRequestAsync(string url, string requestBody, string contentType = "application/json")
        {
            HttpContent content = new StringContent(requestBody, Encoding.UTF8, contentType);
            HttpResponseMessage response = await _client.PostAsync(url, content);
            return await HandleResponseAsync(response);
        }

        public async Task<string> SendPutRequestAsync(string url, string requestBody, string contentType = "application/json")
        {
            HttpContent content = new StringContent(requestBody, Encoding.UTF8, contentType);
            HttpResponseMessage response = await _client.PutAsync(url, content);
            return await HandleResponseAsync(response);
        }

        public async Task<string> SendDeleteRequestAsync(string url)
        {
            HttpResponseMessage response = await _client.DeleteAsync(url);
            return await HandleResponseAsync(response);
        }

        private async Task<string> HandleResponseAsync(HttpResponseMessage response)
        {
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                throw new HttpRequestException($"请求失败: {response.StatusCode}");
            }
        }

        public void Dispose()
        {
            _client.Dispose();
        }
    }
}

在这个示例中,我们创建了一个名为 HttpClientHelper 的工具类,它封装了常见的 HTTP 请求方法,包括 GET、POST、PUTDELETE。你可以根据具体的需求扩展该工具类,并添加其他的方法。

使用时,你可以创建 HttpClientHelper 的实例,并调用其相应的方法来发送 HTTP 请求。可以使用 SetBaseUrl 方法设置基础 URL,使用 SetRequestHeader 方法设置请求头,使用 SetBearerToken 方法设置 Bearer Token 身份验证头。

下面是一个使用示例:

using System;
using System.Threading.Tasks;

namespace YourNamespace
{
    class Program
    {
        static async Task Main(string[] args)
        {
            HttpClientHelper client = new HttpClientHelper();
            client.SetBaseUrl("https://api.example.com");
            client.SetRequestHeader("User-Agent", "YourUserAgent/1.0");

            string url = "/users";
            string responseBody = await client.SendGetRequestAsync(url);
            Console.WriteLine(responseBody);

            string requestBody = "{\"name\": \"John\", \"email\": \"john@example.com\"}";
            string response = await client.SendPostRequestAsync(url, requestBody);
            Console.WriteLine(response);
        }
    }
}

这个示例演示了如何使用封装好的 HttpClientHelper 类发送GET、POST 请求,并获取响应结果。

这样的封装工具类提供了一致的接口和异常处理,同时具备了可扩展性和灵活性,可以满足大部分开发需求。你可以根据具体的项目需求,进一步扩展该工具类,并添加其他功能和方法。