C# 请求第三方API

1、先创建发起请求的类

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace GraspFx.Web.Core.SureWin.HeiHu
{
    public class WebUtils
    {
        private int _timeout = 100000;

        public int Timeout
        {
            get
            {
                return this._timeout;
            }
            set
            {
                this._timeout = value;
            }
        }

     public string DoPost(string url, string data)
        {
            HttpWebRequest webRequest = this.GetWebRequest(url, "POST");
            webRequest.ContentType = "application/json;charset=utf-8";
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();

            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                if (httpWebResponse.CharacterSet != null)
                {
                    encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
                }
                return this.GetResponseAsString(httpWebResponse, encoding);
            }
            catch (WebException ex)
            {
                using (WebResponse response = ex.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    using (Stream sr = response.GetResponseStream())
                    using (var reader = new StreamReader(sr))
                    {
                        string text = reader.ReadToEnd();
                        return text;
                    }
                }
            }
        }

        public string DoPost(string url, string data, Dictionary<string, string> headerParam)
        {
            try
            {
                HttpWebRequest webRequest = this.GetWebRequest(url, "POST");
                webRequest.ContentType = "application/json;charset=utf-8";
                foreach (var item in headerParam)
                {
                    webRequest.Headers.Add(item.Key, item.Value);
                }
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                 if (httpWebResponse.CharacterSet != null)
                {
                    encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
                }
                return this.GetResponseAsString(httpWebResponse, encoding);
            }
            catch (WebException ex)
            {
                return ex.Message;

                using (WebResponse response = ex.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    using (Stream sr = response.GetResponseStream())
                    using (var reader = new StreamReader(sr))
                    {
                        string text = reader.ReadToEnd();
                        return text;
                    }
                }
            }
        }

         public string DoPost(string authorization, string url, string data)
        {
            HttpWebRequest webRequest = this.GetWebRequest(url, "POST");
            webRequest.ContentType = "application/json;charset=utf-8";
            webRequest.Headers.Add(HttpRequestHeader.Authorization, authorization);
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();

            try
            {
                HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                Encoding encoding = Encoding.GetEncoding("UTF-8");
                if (httpWebResponse.CharacterSet != null)
                {
                    encoding = Encoding.GetEncoding(httpWebResponse.CharacterSet);
                }
                return this.GetResponseAsString(httpWebResponse, encoding);
            }
            catch (WebException ex)
            {
                using (WebResponse response = ex.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    using (Stream sr = response.GetResponseStream())
                    using (var reader = new StreamReader(sr))
                    {
                        string text = reader.ReadToEnd();
                        return text;
                    }
                }
            }
        }

        public string DoGet(string url)
        {
            HttpWebRequest webRequest = this.GetWebRequest(url, "GET");
            webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            HttpWebResponse rsp = (HttpWebResponse)webRequest.GetResponse();
            Encoding uTF = Encoding.UTF8;
            return this.GetResponseAsString(rsp, uTF);
        }

        public string DoGet(string url, Dictionary<string, string> headerParam)
        {
            HttpWebRequest webRequest = this.GetWebRequest(url, "GET");
            webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            foreach (var item in headerParam)
            {
                webRequest.Headers.Add(item.Key, item.Value);
            }
            HttpWebResponse rsp = (HttpWebResponse)webRequest.GetResponse();
            Encoding uTF = Encoding.UTF8;
            return this.GetResponseAsString(rsp, uTF);
        }

         public HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest httpWebRequest;
            if (url.Contains("https"))
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
                httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));

                //ServicePointManager.ser

                //httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
            }
            else
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpWebRequest.ServicePoint.Expect100Continue = false;
            httpWebRequest.Method = method;
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Timeout = this._timeout;
            return httpWebRequest;
        }
            public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            //if (sslPolicyErrors == SslPolicyErrors.None) {
            //  return true;
            //}

            //Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

             Do not allow this client to communicate with unauthenticated servers.
            //return false;

            return true;
        }
    
         public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream stream = null;
            StreamReader streamReader = null;
            string result;
            try
            {
                stream = rsp.GetResponseStream();
                streamReader = new StreamReader(stream, encoding);
                result = streamReader.ReadToEnd();
            }
            finally
            {
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (rsp != null)
                {
                    rsp.Close();
                }
            }
            return result;
        }
    }
}

2、再创建一个调用请求方法的类

using Carpa.Web.Script;
using GraspFx.Web.Core.SureWin.HeiHu;
using GraspFx.Web.Core.SureWin.Helper;
using GraspFx.Web.Core.SureWin.Model;
using GraspFx.Web.Core.SureWin.Model.RequestModel;
using GraspFx.Web.Core.SureWin.Model.ResultModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web;

namespace GraspFx.Web.Core.SureWin
{
    public class RequestClient
    {
        private readonly string tokenCacheKey = "HH-Token";
        private readonly string xclient = "lite-web";
        private int _time = 1800;  //过期时间
        private int _minutes = 30;  //过期时间
        private HeiHuConfig _heihuConfig;
        private GjpClient _gjpConfig;
        public RequestClient(HeiHuConfig heihuConfig)
        {
            _heihuConfig = heihuConfig;
            _gjpConfig = new GjpClient();
        }

        /// <summary>
        /// 发起请求
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private string DoRequest(string uri, object data, HttpMethod method)
        {
            string strResult = string.Empty;
            try
            {
                //拼接请求地址
                string url = (_heihuConfig.ApiUrl.StartsWith("http") ? "" : "http://") + _heihuConfig.ApiUrl + uri;
                //返回报文
                string result = GetRequesResult(url, data, method);
                strResult = result;
                return strResult;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 发起请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private string GetRequesResult(string url, object data, HttpMethod method)
        {
            //返回数据
            string result = string.Empty;
            //json字符串数据
            string jsonData = string.Empty;
            if (data != null)
            {
                jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
            }
            //请求头数据
            Dictionary<string, string> dicHeader = new Dictionary<string, string>();
            //token
            string token = string.Empty;
            TokenResult tokenResult = new TokenResult();
            try
            {
                tokenResult = GetToken();
                if (tokenResult.statusCode == "200")
                {
                    token = tokenResult.data;
                }
                else
                {
                    return "token获取失败:" + tokenResult.message;
                }
            }
            catch (Exception ex)
            {
                return "token获取异常:" + ex.Message;
            }
            dicHeader.Add("X-AUTH", token);

            if (method == HttpMethod.Get)
            {
                result = new WebUtils().DoGet(url, dicHeader);
            }
            else
            {
                result = new WebUtils().DoPost(url, jsonData, dicHeader);
            }
            return result;
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        private TokenResult GetToken()
        {
            TokenResult tokenResult = new TokenResult();
            try
            {
                //存在token信息直接返回
                string token = string.Empty;
                //缓存中取
                object obj = HttpRuntime.Cache.Get(tokenCacheKey);
                if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
                {
                    tokenResult.statusCode = "200";
                    tokenResult.data = obj.ToString();
                    return tokenResult;
                }
                else
                {
                    //添加日志
                    HeiHuLog log = new HeiHuLog();
                    log.RequestTime = DateTime.Now;
                    log.Operation = "获取Token";
                    //请求地址
                    string url = (_heihuConfig.ApiUrl.StartsWith("http") ? "" : "http://") + _heihuConfig.ApiUrl + "/api/user/v1/users/_login";
                    log.Url = url;

                     //添加请求头参数
                    Dictionary<string, string> headerParam = new Dictionary<string, string>();
                    headerParam.Add("x-client", xclient);

                    //请求数据
                    HashObject data = new HashObject();
                    if (_heihuConfig.Type == 0)
                    {
                        data["phone"] = _heihuConfig.Phone;
                        data["password"] = _heihuConfig.PassWord.SHA3_224();
                    }
                    else
                    {
                        data["code"] = _heihuConfig.Code;
                        data["username"] = _heihuConfig.Username;
                        data["type"] = _heihuConfig.Type;
                        data["password"] = _heihuConfig.PassWord.SHA3_224();
                    }

                     //请求报文
                    string requestData = JsonConvert.SerializeObject(data, Formatting.Indented);
                    log.RequestSrting = requestData;

                    //请求接口
                    string result = new WebUtils().DoPost(url, requestData, headerParam);
                    log.ResponseString = result;

                    //json转实体类
                    try
                    {
                        tokenResult = JsonConvert.DeserializeObject<TokenResult>(result);
                    }
                    catch (Exception)
                    {
                        tokenResult.statusCode = "-1";
                        tokenResult.message = result;
                    }

                    log.Code = tokenResult.statusCode;
                    log.Message = tokenResult.message;

                    if (tokenResult.statusCode == "200")
                    {
                        //获取到添加到缓存
                        token = tokenResult.data;
                        TimeSpan ts = new TimeSpan(0, 0, _time);
                        HttpRuntime.Cache.Insert(tokenCacheKey, token, null, DateTime.Now.AddMinutes(_minutes), ts);

                        //添加日志
                        log.Success = true;
                        
                    }
                    else
                    {
                        //添加日志
                        log.Success = false;

                        tokenResult.message = string.Format("获取Token失败:{0},{1}", tokenResult.statusCode, tokenResult.message);
                        //抛出异常
                        //throw new Exception(string.Format("获取Token失败:{0},{1}", tokenResult.stat

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/582919.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Docker基本操作 Linux里边操作

docker镜像操作命令: docker images:查看所有镜像; docker rmi:删除镜像 后边可以跟镜像的名字或者id指定要删除的镜像&#xff1b; docker pull:拉取镜像&#xff1b; docker push:推送镜像到服务&#xff1b; docker save :打包镜像 后边有用法; docker load:加载镜像&…

前端JS必用工具【js-tool-big-box】,字符串反转,驼峰转换以及版本号对比

这一小节&#xff0c;我们针对前端工具包&#xff08;npm&#xff09;js-tool-big-box的使用做一些讲解&#xff0c;主要是针对字符串反转&#xff0c;aa-bb-cc转驼峰&#xff0c;以及版本号对比的内容 目录 1 安装和引入 2 字符串反转 3 带有横岗的转驼峰 3.1 转小驼峰 3…

docker-compose编排集成工具,

一、引言 我们知道使用一个 Dockerfile 模板文件可以定义一个单独的应用容器&#xff0c;如果需要定义多个容器就需要服务编排。服务编排有很多种技术方案&#xff0c;今天给大家介绍 Docker 官方产品 Docker-Compose Dockerfile 可以定义一个单独的应用容器&#xff1…

linux,从零安装mysql 8.0.30 ,并且更新至mysql 8.0.36

前言&#xff1a; 系统使用的CentOS 7&#xff0c;系统默认最小安装。 一、基础配置 配置虚拟机IP&#xff0c;需要更改的内容&#xff0c;如下红框中 修改之后 至此&#xff0c;基础配置完成。注意&#xff1a;此处虚拟机网络适配器使用的是&#xff1a;桥接模式 二、软件…

【问题实操】银河麒麟高级服务器操作系统实例,CPU软锁报错触发宕机

1.服务器环境以及配置 处理器&#xff1a; Kunpeng 920 内存&#xff1a; 256G DDR4 整机类型/架构&#xff1a; TaiShan 200 (Model 2280) 内核版本 4.19.90-23.8.v2101.ky10.aarch64 2.问题现象描述 两台搭载麒麟v10 sp1的机器均在系统CPU软锁报错时&#xff0c;触…

Springboot+mybatis升级版(Postman测试)

一、项目结构 1.导入依赖 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apach…

高级数据结构与算法期中测试题

一、判断题 1、In dynamic programming algorithms, some results of subproblems have to be stored even they do not compose the optimal solution of a larger problem. T F 解析:T。在动态规划算法中,必须存储子问题的某些结果,因为他们可能需要用来…

区块链技术:NFG元宇宙电商模式

大家好&#xff0c;我是微三云周丽 随着互联网技术的迅猛发展&#xff0c;电子商务行业逐渐崛起为现代经济的重要支柱。而在这一浪潮中&#xff0c;元宇宙电商以其独特的商业模式和巨大的发展潜力&#xff0c;成为行业的新宠。其中&#xff0c;NFG作为元宇宙电商模式的代表&am…

【4110】基于小程序实现的名片管理系统

作者主页&#xff1a;Java码库 主营内容&#xff1a;SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app等设计与开发。 收藏点赞不迷路 关注作者有好处 文末获取源码 技术选型 【后端】&#xff1a;Java 【框架】&#xff1a;spring…

std::ignore的定义

有个全局变量。 把一个变量赋值给ignore&#xff0c;还行&#xff0c;没有拷贝等动作&#xff0c;不用担心性能损失。 VS2017D:\DevTools\VS2017\VC\Tools\MSVC\14.16.27023\include\tuple// STRUCT _Ignore struct _Ignore{ // struct that ignores assignmentstemplate<…

如何利用 GPT 自我提高写作能力

GPT革命&#xff1a;如何用AI技术重新定义写作 介绍 在我们的数字时代&#xff0c;了解自我提高写作的必要性至关重要。 随着 GPT 的兴起&#xff0c;我们正在见证书写的变革时代。 这篇扩展文章深入探讨了 GPT 如何显着提高写作技能。 拥抱未来&#xff1a; 人工智能时代的写…

Oracle 数据迁移同步优化(三)

简述 CloudCanal 最近再次对其 Oracle 源端数据同步进行了一系列优化&#xff0c;这些优化基于用户在真实场景中的反馈&#xff0c;具备很强的生产级别参考意义。 本文将简要介绍这些优化项&#xff0c;希望带给读者一些收获。 增量事件 SCN 乱序问题MISSING_SCN 事件干扰新…

物联网和互联网有什么区别?从多个方面进行探讨——青创智通

工业物联网解决方案-工业IOT-青创智通 物联网和互联网是现代信息技术的两大重要领域&#xff0c;它们在许多方面有着紧密的联系&#xff0c;但也有着明显的区别。本文将从多个方面对物联网和互联网的区别进行探讨。 首先&#xff0c;从定义上来看&#xff0c;互联网是一种全球…

38.WEB渗透测试-信息收集-信息收集-企业信息收集(5)

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 内容参考于&#xff1a; 易锦网校会员专享课 上一个内容&#xff1a;37.WEB渗透测试-信息收集-企业信息收集&#xff08;4&#xff09; 上个内容用到了cdn&am…

【赠书活动第3期】《PyTorch 2.0深度学习从零开始学》

1. 赠书活动 《PyTorch 2.0深度学习从零开始学》免费赠书 5 本&#xff0c; 可在本帖评论中简单评论一下本书的优缺点&#xff0c; 或者在本帖评论中简单写一下你学习PyTorch想要达到什么目的&#xff0c; 博主从本帖评论中写得较好的朋友中选5人赠送。 截止日期为2024年5…

leetcode-有效括号序列-94

题目要求 思路 1.使用栈的先进后出的思路&#xff0c;存储前括号&#xff0c;如果st中有对应的后括号与之匹配就说明没问题 2.有两个特殊情况就是字符串第一个就是后括号&#xff0c;这个情况本身就是不匹配的&#xff0c;还有一种是前面的n个字符串本身是匹配的&#xff0c;这…

vue3插槽的name和v-slot的研究

slot可以分为具名插槽和默认,默认插槽name是default 在父组件的template需要些v-slot/#,没写不生效,而在父组件下,而没被template包含的默认放在template且含有#default. 1)没写slot,可以不写template,也可写default的template2)写了name的slot,即使是default也必须些template…

内外网隔离后 内网文件如何导出?

将内外网进行网络隔离后&#xff0c;内网文件如何导出&#xff1f;怎样确保安全的前提下&#xff0c;不影响业务的正常开展&#xff1f;这时候企业就需要采取安全且合规的方法来确保数据的安全性和防止未授权访问。 企业会采用的传统流程是&#xff1a;当文件由内网导出至外部时…

javaWeb项目-校园志愿者管理系统功能介绍

项目关键技术 开发工具&#xff1a;IDEA 、Eclipse 编程语言: Java 数据库: MySQL5.7 框架&#xff1a;ssm、Springboot 前端&#xff1a;Vue、ElementUI 关键技术&#xff1a;springboot、SSM、vue、MYSQL、MAVEN 数据库工具&#xff1a;Navicat、SQLyog 1、SpringBoot框架 …

书生·浦语 大模型(学习笔记-8)Lagent AgentLego 智能体应用搭建

目录 一、智能体出现的原因 二、智能体的定义 三、智能体的组成 四、Lagent 五、AgentLego 六、实战一&#xff08;Lagent&#xff09; 环境配置及安装 安装依赖 准备 Tutorial Lagent Web Demo AgentLego 使用 图片推理&#xff08;结果&#xff09;&#xff1a; …