当前位置: 首页 > news >正文

C#底层库–网络通信帮助类HTTP

系列文章

C#底层库–记录日志帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709

C#底层库–数据库访问帮助类(MySQL版)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871

C#底层库–操作文件帮助类FileHelper(获取目录的所有文件)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161

C#底层库–操作Excel帮助类(读取、导出表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445

C#底层库–软件版本管理XML
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110195766

C#底层库–随机数生成类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812

C#RegexHelper正则表达式帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286

文章目录

  • 系列文章
  • 前言
  • 一、底层库介绍
  • 二、底层库源码
  • 三、调用方法
  • 四、运行效果


前言

文将新增一个专栏–底层库,分享编程过程中常用的方法函数。我们将这些常用的方法函数,进行封装,反复测试,形成通用化类库。
方便研发人员,只需要几行代码就可以使用它,解决一些难点问题。
底层库的封装涉及到:数据库操作、加解密算法、日志记录、网络通信、邮件发送、文件操作、参数保存、Excel导入导出等等,持续关注本专栏吧。大家有任何问题,也可以评论区反馈,私信我。

一、底层库介绍

网络访问帮助类,采用HTTP方式访问服务端,包含get、post、put、delete。

二、底层库源码

创建类HttpHelper.cs,复制以下代码

using System;
using System.IO;
using System.Net;
using System.Text;

namespace QRCodeProduce.BLL
{
    public class HttpHelper
    {
        /// <summary>
        /// Get方法
        /// </summary>
        /// <param name="a_ParamData">?a_fileName=20220908-2.apk</param>
        /// <param name="Url">url</param>
        /// <returns></returns>
        public static string HttpGet(string Url, string a_ParamData)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(a_ParamData);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
                webRequest.Method = "GET";
                webRequest.Accept = "application/json, text/javascript, */*";  // 出错就删掉
                webRequest.ContentType = "application/json; charset=utf-8";
                webRequest.ContentLength = byteArray.Length;

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd(); // 返回的数据
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body">{ "no": "A28A1MW43C"}</param>
        /// <returns></returns>
        public static string HttpPost(string url, string body)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "POST";
                webRequest.Accept = "application/json, text/javascript, */*";
                webRequest.ContentType = "application/json; charset=utf-8";
                webRequest.ContentLength = byteArray.Length;
                webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Put请求
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="body">application/json</param>
        /// <returns></returns>
        public static string HttpPut(string url, string body)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "PUT";
                webRequest.Accept = "application/json, text/javascript, */*";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = byteArray.Length;
                webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Delete请求
        /// </summary>
        /// <param name="url">URL</param>
        /// <param name="body">application/json</param>
        /// <returns></returns>
        public static string HttpDelete(string url, string body)
        {
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(body);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "DELETE";
                webRequest.Accept = "application/json, text/javascript, */*";
                webRequest.ContentType = "application/json";
                webRequest.ContentLength = byteArray.Length;
                webRequest.GetRequestStream().Write(byteArray, 0, byteArray.Length);

                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }

}

三、调用方法

我这里是写了一个button按钮,扫码获得编号,然后点击读取标签,直接可以获得数据。

  private void BTN_Scan_Click(object sender, EventArgs e)
        {
            ScanModel model = new ScanModel
            {
                no = baseDataInput_原料编号.StringValue
            }; 
       
            string l_strYuanLiaoBianhao = JsonConvert.SerializeObject(model);

            string l_strReturn = HttpHelper.HttpPost(string.Format(Const.ct_strScanHSLabel, AppConfig.GetValue("db_server")), l_strYuanLiaoBianhao);

            ActionResult Result = JsonConvert.DeserializeObject<ActionResult>(l_strReturn);

            if (Result.RetInfo.IsSUCD)
            {
                Dictionary<string, string> dicResult = new Dictionary<string, string>();
                dicResult.Clear();

                JObject jo1 = (JObject)JsonConvert.DeserializeObject(Result.Data.Obj.ToString());//JSON反序列化
                foreach (var item in jo1)
                {
                    dicResult.Add(item.Key, item.Value.ToString());
                }

                baseDataInput_原料规格.StringValue = dicResult["黄丝规格"];
                baseDataInput_原料强度.StringValue = dicResult["强度代号"];
                baseDataInput_黄丝厂家.StringValue = dicResult["黄丝厂家"];
                baseDataInput_黄丝代码.StringValue = dicResult["黄丝代码"];
                baseDataInput_doff.StringValue = dicResult["doff"];
            }
            else
            {
                XtraMessageBox.Show(Result.RetInfo.ErrorCode + ":" + Result.RetInfo.ErrorMsg,
                 "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

数据结构ScanModel.cs

    public class ScanModel
    {
        public string no { get; set; }
    }

四、运行效果

PC连接扫码枪,扫描一维码、二维码标签,自动复制“原料编号”,点击“读标”按钮自动获取标签信息。
在这里插入图片描述

相关文章:

  • shell脚本练习及小总结
  • 青岛大学数据结构与算法——第2章
  • tf.math
  • GBase 8c向表中插入数据
  • 想要软考,一般需要多少复习时间?
  • 一起误删cni0虚拟网卡引发的k8s事故
  • QT软件开发-基于FFMPEG设计录屏与rtsp、rtmp推流软件(支持桌面与摄像头)(四)
  • redux中间件函数
  • 【前端面试知识题】- 4.1 JavaScript
  • 客户端架构
  • iOS Xcode 14 创建新项目Pod init及Pod install 报错
  • 金融行业借力泛微今承达,合同统一数字化管理、风险全过程把控
  • 计算机视觉项目实战-基于特征点匹配的图像拼接
  • 软件过程与建模学习之:Individuals,Motivation and Teams
  • 【某南方·高中梦校面试】
  • 【干货分享】SpringCloud微服务架构分布式组件如何共享session对象
  • 5、React组件事件详解
  • Android 控件背景颜色处理
  • iOS编译提示和导航提示
  • Java 23种设计模式 之单例模式 7种实现方式
  • Selenium实战教程系列(二)---元素定位
  • Synchronized 关键字使用、底层原理、JDK1.6 之后的底层优化以及 和ReenTrantLock 的对比...
  • Vue学习第二天
  • 开发了一款写作软件(OSX,Windows),附带Electron开发指南
  • 智能网联汽车信息安全
  • 支付宝花15年解决的这个问题,顶得上做出十个支付宝 ...
  • #ifdef 的技巧用法
  • #if和#ifdef区别
  • (1/2)敏捷实践指南 Agile Practice Guide ([美] Project Management institute 著)
  • (13):Silverlight 2 数据与通信之WebRequest
  • (2015)JS ES6 必知的十个 特性
  • (4.10~4.16)
  • (备忘)Java Map 遍历
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (力扣)循环队列的实现与详解(C语言)
  • (顺序)容器的好伴侣 --- 容器适配器
  • (转)setTimeout 和 setInterval 的区别
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • .NET6 开发一个检查某些状态持续多长时间的类
  • .Net的DataSet直接与SQL2005交互
  • @RequestMapping 的作用是什么?
  • [Android]一个简单使用Handler做Timer的例子
  • [C++] 统计程序耗时
  • [CISCN 2023 初赛]go_session
  • [docker] Docker的数据卷、数据卷容器,容器互联
  • [Git].gitignore失效的原因
  • [HNOI2015]实验比较
  • [IE编程] 如何获得IE版本号
  • [linux]centos7下解决yum install mysql-server没有可用包
  • [nlp] 损失缩放(Loss Scaling)loss sacle
  • [Notice] 朋友们,blog更新http://jiang-hongfei.spaces.live.com
  • [POJ 1915] Knight Moves
  • [ruby on rails] ruby使用vscode做开发
  • [svc]logstash和filebeat之间ssl加密
  • [WeChall] No Escape (Exploit, PHP, MySQL)