基于 .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】文件,点击下载;

目录
相关文章
|
20天前
|
JSON 监控 API
掌握使用 requests 库发送各种 HTTP 请求和处理 API 响应
本课程全面讲解了使用 Python 的 requests 库进行 API 请求与响应处理,内容涵盖环境搭建、GET 与 POST 请求、参数传递、错误处理、请求头设置及实战项目开发。通过实例教学,学员可掌握基础到高级技巧,并完成天气查询应用等实际项目,适合初学者快速上手网络编程与 API 调用。
304 130
|
1月前
HTTP协议中请求方式GET 与 POST 什么区别 ?
GET和POST的主要区别在于参数传递方式、安全性和应用场景。GET通过URL传递参数,长度受限且安全性较低,适合获取数据;而POST通过请求体传递参数,安全性更高,适合提交数据。
343 2
|
3月前
|
JavaScript 前端开发 API
Node.js中发起HTTP请求的五种方式
以上五种方式,尽管只是冰山一角,但已经足以让编写Node.js HTTP请求的你,在连接世界的舞台上演奏出华丽的乐章。从原生的 `http`到现代的 `fetch`,每种方式都有独特的风格和表现力,让你的代码随着项目的节奏自由地舞动。
435 65
|
2月前
|
Go 定位技术
Golang中设置HTTP请求代理的策略
在实际应用中,可能还需要处理代理服务器的连接稳定性、响应时间、以及错误处理等。因此,建议在使用代理时增加适当的错误重试机制,以确保网络请求的健壮性。此外,由于网络编程涉及的细节较多,彻底测试以确认代理配置符合预期的行为也是十分重要的。
140 8
|
2月前
|
缓存
|
1月前
|
JSON JavaScript API
Python模拟HTTP请求实现APP自动签到
Python模拟HTTP请求实现APP自动签到
|
1月前
|
数据采集 JSON Go
Go语言实战案例:实现HTTP客户端请求并解析响应
本文是 Go 网络与并发实战系列的第 2 篇,详细介绍如何使用 Go 构建 HTTP 客户端,涵盖请求发送、响应解析、错误处理、Header 与 Body 提取等流程,并通过实战代码演示如何并发请求多个 URL,适合希望掌握 Go 网络编程基础的开发者。
|
2月前
|
缓存 JavaScript 前端开发
Vue 3 HTTP请求封装导致响应结果无法在浏览器中获取,尽管实际请求已成功。
通过逐项检查和调试,最终可以定位问题所在,修复后便能正常在浏览器中获取响应结果。
170 0
|
2月前
|
Go
如何在Go语言的HTTP请求中设置使用代理服务器
当使用特定的代理时,在某些情况下可能需要认证信息,认证信息可以在代理URL中提供,格式通常是:
242 0
|
4月前
|
Go
在golang中发起http请求以获取访问域名的ip地址实例(使用net, httptrace库)
这只是追踪我们的行程的简单方法,不过希望你跟着探险家的脚步,即使是在互联网的隧道中,也可以找到你想去的地方。接下来就是你的探险之旅了,祝你好运!
183 26

热门文章

最新文章