基于 .NET Core 2.2 的 Console 控制台实现简单 HTTP 请求的【CRUD】操作

简介: Demo 说明:该项目是基于 .NET Core 2.2 的 Console 控制台实现简单的 http 模拟请求,对应http谓词实现的CRUD的封装操作;本项目依赖的 NuGet 包:Microsoft.AspNetCore.Http.Abstractions;Newtonsoft.Json;RestSharp;<Project Sdk="Microsoft.NET.Sdk"...

Demo 说明

该项目是基于 .NET Core 2.2Console 控制台实现简单的 http 模拟请求,对应 http 谓词实现的 CRUD 的封装操作;

本项目依赖的 NuGet 包:

  • Microsoft.AspNetCore.Http.Abstractions;
  • Newtonsoft.Json;
  • RestSharp;
<Project Sdk="Microsoft.NET.Sdk">
 
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
 
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="RestSharp" Version="106.6.10" />
  </ItemGroup>
 
</Project>

image.png

数据交互响应模型:ResponseModel

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApi
{
    /// <summary>
    /// 公共响应模型
    /// </summary>
    public sealed class ResponseModel
    {
        /// <summary>
        /// 响应码
        /// </summary>
        public int Code { get; set; }

        /// <summary>
        /// 响应状态
        /// </summary>
        public bool Success { get; set; }
 
        /// <summary>
        /// 提示信息
        /// </summary>
        public string Msg { get; set; }
 
        /// <summary>
        /// 数据包(jsonString)
        /// </summary>
        public object Data { get; set; }
    }
}

API 参数配置模型:ApiConfigModel

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApi
{
    /// <summary>
    /// api 配置模型
    /// </summary>
    public class ApiConfigModel
    {
        /// <summary>
        /// api地址
        /// </summary>
        public string HostAddress { get; set; }
 
        /// <summary>
        /// 客户端访问类型
        /// </summary>
        public string ContentType { get; set; } = "PC";
 
        /// <summary>
        /// 访问账号
        /// </summary>
        public string Account { get; set; }
 
        /// <summary>
        /// Token
        /// </summary>
        public string Token { get; set; }
 
        /// <summary>
        /// 报文数据发送类型
        /// </summary>
        public string ClientType { get; set; } = "application/json";
 
        /// <summary>
        /// api版本号
        /// </summary>
        public string Version { get; set; } = "v1";
    }
}

封装简易 Http-API 助手:SimpleHttpApiHelper

using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApi
{
    /// <summary>
    /// 简易Http-API助手
    /// </summary>
    public class SimpleHttpApiHelper
    {
        #region 单例模式
        //创建私有化静态obj锁  
        private static readonly object _ObjLock = new object();
        //创建私有静态字段,接收类的实例化对象  
        private static SimpleHttpApiHelper _SimpleHttpApiHelper = null;
        //构造函数私有化  
        private SimpleHttpApiHelper() { }
        //创建单利对象资源并返回  
        public static SimpleHttpApiHelper GetSingleObj()
        {
            if (_SimpleHttpApiHelper == null)
            {
                lock (_ObjLock)
                {
                    if (_SimpleHttpApiHelper == null)
                    {
                        _SimpleHttpApiHelper = new SimpleHttpApiHelper();
                    }
                }
            }
            return _SimpleHttpApiHelper;
        }
        #endregion
 
        #region 参数配置
        private static string _HostAddress;
        private static string _ContentType;
        private static string _Account;
        private static string _Token;
        private static string _ClientType;
        private static string _Version;
 
        /// <summary>
        /// 初始化参数配置项
        /// </summary>
        /// <param name="hostAddress">api地址</param>
        /// <param name="account">访问账号</param>
        /// <param name="token">Token</param>
        /// <param name="contentType">报文数据发送类型</param>
        /// <param name="clientType">客户端访问类型</param>
        /// <param name="version">api版本号</param>
        public void SetApiConfig(string hostAddress, string account, string token, string contentType = "application/json", string clientType = "PC", string version = "v1")
        {
            if (string.IsNullOrWhiteSpace(hostAddress) || string.IsNullOrWhiteSpace(account) || string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(contentType))
                throw new NullReferenceException("参数空异常!");
            else if (!account.Contains("|"))
                throw new FormatException("Account约定格式异常!");
 
            _HostAddress = hostAddress;
            _ContentType = contentType;
            _Account = account;
            _Token = token;
            _ClientType = clientType;
            _Version = version;
        }
 
        /// <summary>
        /// 初始化参数配置项
        /// </summary>
        /// <param name="model"></param>
        public void SetApiConfig(ApiConfigModel model)
        {
            if (string.IsNullOrWhiteSpace(model.HostAddress) || string.IsNullOrWhiteSpace(model.Account) || string.IsNullOrWhiteSpace(model.Token) || string.IsNullOrWhiteSpace(model.ContentType))
                throw new NullReferenceException("参数空异常!");
            else if (!model.Account.Contains("|"))
                throw new FormatException("Account约定格式异常!");
 
            _HostAddress = model.HostAddress;
            _ContentType = model.ContentType;
            _Account = model.Account;
            _Token = model.Token;
            _ClientType = model.ClientType;
            _Version = model.Version;
        }
        #endregion
 
        #region 实现HTTP的【CRUD】操作
        public enum HttpMethod { GET, POST, PUT, DELETE };
        private string GetHttpMethod(HttpMethod httpMethod)
        {
            string _HttpMethod = string.Empty;
            switch (httpMethod)
            {
                case HttpMethod.GET:
                    _HttpMethod = "GET";
                    break;
                case HttpMethod.POST:
                    _HttpMethod = "POST";
                    break;
                case HttpMethod.PUT:
                    _HttpMethod = "PUT";
                    break;
                case HttpMethod.DELETE:
                    _HttpMethod = "DELETE";
                    break;
            }
            return _HttpMethod;
        }
 
        /// <summary>
        /// HttpWebRequest 方式实现【CRUD】
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="httpMethod"></param>
        /// <param name="controller"></param>
        /// <param name="actionCode"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public T CreateHttpWebRequest<T>(HttpMethod httpMethod, string controller, string actionCode, string postDataStr = "")
        {
            string apiUrl = $"{_HostAddress}/{_Version}/{controller}/{actionCode}";
            var request = WebRequest.Create(apiUrl + (string.IsNullOrWhiteSpace(postDataStr) ? "" : "?") + postDataStr) as HttpWebRequest;
            request.Method = GetHttpMethod(httpMethod);
            request.ContentType = _ContentType; //"text/html;charset=UTF-8";
            request.Headers["Account"] = _Account;
            request.Headers["Token"] = _Token;
            request.Headers["ClientType"] = _ClientType;
 
            string jsonString = string.Empty;
            var response = request.GetResponse() as HttpWebResponse;
            using (Stream myResponseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8")))
                {
                    Task<string> task = myStreamReader.ReadToEndAsync();
                    jsonString = task.Result;
                    //myStreamReader.Close();
                    //myResponseStream.Close();
                }
            }
            if (string.IsNullOrWhiteSpace(jsonString))
                return default;
            else
                return JsonConvert.DeserializeObject<T>(jsonString);
        }
 
        /// <summary>
        /// WebClient 方式实现【CRUD】
        /// </summary>
        /// <param name="method"></param>
        /// <param name="controller"></param>
        /// <param name="actionCode"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public JsonObject CreateWebClientRequest(HttpMethod httpMethod, string controller, string actionCode, JsonObject data)
        {
            string apiUrl = $"{_HostAddress}/{_Version}/{controller}/{actionCode}";
            string jsonData = data == null ? string.Empty : data.ToString(); //请求参数
            string jsonString = null; //响应数据
            using (WebClient wc = new WebClient())
            {
                wc.Headers["Content-Type"] = _ContentType;//"application/x-www-form-urlencoded";
                wc.Headers["Account"] = _Account;
                wc.Headers["Token"] = _Token;
                wc.Headers["ClientType"] = _ClientType;
                wc.Encoding = Encoding.UTF8;
                Task<string> task = wc.UploadStringTaskAsync(apiUrl, GetHttpMethod(httpMethod), jsonData);
                jsonString = task.Result;
            }
            if (string.IsNullOrWhiteSpace(jsonString))
                return new JsonObject();
            else
                return JsonConvert.DeserializeObject<JsonObject>(jsonString);
        }
 
        #endregion
        /// <summary>
        ///  异常捕获器
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <typeparam name="T3"></typeparam>
        /// <typeparam name="T4"></typeparam>
        /// <typeparam name="TR"></typeparam>
        /// <param name="func"></param>
        /// <param name="t1"></param>
        /// <param name="t2"></param>
        /// <param name="t3"></param>
        /// <param name="t4"></param>
        /// <returns></returns>
        public static TR ExceptionTrapper<T1,T2,T3,T4,TR>(Func<T1, T2, T3, T4, TR> func, T1 t1, T2 t2, T3 t3, T4 t4) 
        {
            try
            {
               return func(t1,t2,t3,t4);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
 
        #region 简化封装-委托调用
        public T HttpWebRequest<T>(HttpMethod httpMethod, string controller, string actionCode, string postDataStr = "")
        {
            return ExceptionTrapper(CreateHttpWebRequest<T>, httpMethod, controller, actionCode, postDataStr);
        }
 
        public JsonObject HttpWebRequest(HttpMethod httpMethod, string controller, string actionCode, JsonObject data)
        {
            return ExceptionTrapper(CreateWebClientRequest, httpMethod, controller, actionCode, data);
        } 
        #endregion
    }
}

Console 控制台调用:

using RestSharp;
using System;
using System.Collections.Generic;
 
namespace ConsoleApi
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello http!");
 
            //1.配置注册(重载实现)
            string hostAddress = "http://192.168.10.231:9003/api"; //此处写约定格式的api地址
            string account = "666|xxx";
            string token = "token";
            //SimpleHttpApiHelper.GetSingleObj().SetApiConfig(hostAddress, account, token); //参数方式
            SimpleHttpApiHelper.GetSingleObj().SetApiConfig(new ApiConfigModel { HostAddress= hostAddress, Account= account, Token = token }); //模型方式
 
            //2.原生调用(未添加异常捕获)
            var json = SimpleHttpApiHelper.GetSingleObj().CreateHttpWebRequest<ResponseModel>(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var jsonObj = SimpleHttpApiHelper.GetSingleObj().CreateWebClientRequest(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
 
            //3.委托调用(添加异常捕获)
            var s1 = SimpleHttpApiHelper.ExceptionTrapper<SimpleHttpApiHelper.HttpMethod, string, string, JsonObject, JsonObject>(SimpleHttpApiHelper.GetSingleObj().CreateWebClientRequest, SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var s2 = SimpleHttpApiHelper.ExceptionTrapper<SimpleHttpApiHelper.HttpMethod, string, string, string, ResponseModel>(SimpleHttpApiHelper.GetSingleObj().CreateHttpWebRequest<ResponseModel>, SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
 
            //4.简化封装-委托调用(添加异常捕获)
            var s3 = SimpleHttpApiHelper.GetSingleObj().HttpWebRequest<string>(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
            var s4 = SimpleHttpApiHelper.GetSingleObj().HttpWebRequest(SimpleHttpApiHelper.HttpMethod.POST, "Open", "1001", null);
 
            Console.ReadKey();
        }
    }
}

以上简单示例完毕,Demo 下载链接:https://download.csdn.net/my/uploads 选择 【ConsoleApi.zip】文件,点击下载;

目录
相关文章
|
3月前
|
程序员 开发者
IDEA插件-Grep Console彩色控制台
IDEA插件-Grep Console是一款用于增强IDEA开发环境的工具,它可以帮助开发者更好地搜索和过滤控制台输出。
307 0
IDEA插件-Grep Console彩色控制台
|
2月前
|
数据采集 JSON API
异步方法与HTTP请求:.NET中提高响应速度的实用技巧
本文探讨了在.NET环境下,如何通过异步方法和HTTP请求提高Web爬虫的响应速度和数据抓取效率。介绍了使用HttpClient结合async和await关键字实现异步HTTP请求,避免阻塞主线程,并通过设置代理IP、user-agent和cookie来优化爬虫性能。提供了代码示例,演示了如何集成这些技术以绕过目标网站的反爬机制,实现高效的数据抓取。最后,通过实例展示了如何应用这些技术获取API的JSON数据,强调了这些方法在提升爬虫性能和可靠性方面的重要性。
异步方法与HTTP请求:.NET中提高响应速度的实用技巧
|
4天前
|
API
使用`System.Net.WebClient`类发送HTTP请求来调用阿里云短信API
使用`System.Net.WebClient`类发送HTTP请求来调用阿里云短信API
11 0
|
4天前
|
安全 网络安全 数据安全/隐私保护
HTTPS 请求中的证书验证详解(Python版)
HTTPS 请求中的证书验证详解(Python版)
11 0
|
2月前
|
数据采集 API 开发者
.NET 8新特性:使用ConfigurePrimaryHttpMessageHandler定制HTTP请求
在.NET 8中,通过`ConfigurePrimaryHttpMessageHandler`方法,开发者能更精细地控制HTTP请求,这对于构建高效爬虫尤为重要。此特性支持定制代理IP、管理Cookie与User-Agent,结合多线程技术,有效应对网络限制及提高数据采集效率。示例代码展示了如何设置代理服务器、模拟用户行为及并发请求,从而在遵守网站规则的同时,实现快速稳定的数据抓取。
.NET 8新特性:使用ConfigurePrimaryHttpMessageHandler定制HTTP请求
|
2月前
|
Unix Linux C#
增强用户体验:2个功能强大的.NET控制台应用帮助库
增强用户体验:2个功能强大的.NET控制台应用帮助库
|
2月前
|
数据采集 开发框架 .NET
HttpClient在ASP.NET Core中的最佳实践:实现高效的HTTP请求
在现代Web开发中,高效可靠的HTTP请求对应用性能至关重要。ASP.NET Core提供的`HttpClient`是进行这类请求的强大工具。本文探讨其最佳实践,包括全局复用`HttpClient`实例以避免性能问题,通过依赖注入配置预设头部信息;使用代理IP以防IP被限制;设置合理的`User-Agent`和`Cookie`来模拟真实用户行为,提高请求成功率。通过这些策略,可显著增强爬虫或应用的稳定性和效率。
HttpClient在ASP.NET Core中的最佳实践:实现高效的HTTP请求
|
3月前
|
安全 Java 网络安全
RestTemplate进行https请求时适配信任证书
RestTemplate进行https请求时适配信任证书
66 3
|
2月前
|
JavaScript 前端开发 Java
【Azure 环境】各种语言版本或命令,发送HTTP/HTTPS的请求合集
【Azure 环境】各种语言版本或命令,发送HTTP/HTTPS的请求合集
|
3月前
|
文字识别 前端开发 API
印刷文字识别操作报错合集之通过HTTPS连接到OCR服务的API时报错,该如何处理
在使用印刷文字识别(OCR)服务时,可能会遇到各种错误。例如:1.Java异常、2.配置文件错误、3.服务未开通、4.HTTP错误码、5.权限问题(403 Forbidden)、6.调用拒绝(Refused)、7.智能纠错问题、8.图片质量或格式问题,以下是一些常见错误及其可能的原因和解决方案的合集。