借助HttpWebRequest 调用第三方接口,获取Token和数据

在一次项目中,在给客户做系统时,需要调用客户的系统获取数据,客户提供了获取Token和获取数据的接口,用户名和密码,认证方式是基于Bearer的,通过学习和找资料,提供一个C#示例

一个C#示例

1、传入语句获取数据
         /// <summary>
        /// 传入语句获取数据
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<string> ThirdSystemDataPostAsync(string param,string dataUrlAddress)
        {
            string token = await Bearer_TokenPostAsync();
            _logger.Warn($"获取Token结构:{token}");
            string responseString = string.Empty;
            try
            {
                var tokenJson = JsonConvert.DeserializeObject<TokenResultDto>(token);
                _logger.Warn($"获取Token值参数据:{tokenJson}");

                //跳过ssl验证
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                // 创建HttpWebRequest对象
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(dataUrlAddress);
                _logger.Warn($"入参数据:{param}");
                _logger.Warn($"智慧系统数据地址:{dataUrlAddress}");
                // 设置Post调⽤⽅法
                httpRequest.Method = "Post";
                //设置参数传输类型
                httpRequest.ContentType = " application/json; charset=utf-8";
                // 设置Http Bearer认证的请求头
                httpRequest.Headers.Add("Authorization", "Bearer " + tokenJson.accessToken);
                //传输参数格式转换
                byte[] bytesRequestData = Encoding.UTF8.GetBytes(param);
                //_logger.Warn($"入参数据格式转换:{bytesRequestData}");
                httpRequest.ContentLength = bytesRequestData.Length;
                Stream postStream = await httpRequest.GetRequestStreamAsync();
                postStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                postStream.Close();
                //获取设置身份认证及请求超时时间
                SetWebRequest(httpRequest);
                // HttpWebRequest发起调⽤
                using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
                {
                    //myResponse.StatusCode
                    // StreamReader对象
                    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                    // 返回结果
                    responseString = sr.ReadToEnd();

                    _logger.Warn($"调用智慧系统返回结果数据:{responseString}");
                    return responseString;
                }
            }
            catch (Exception ex)
            {
                //返回错误信息
                responseString = ex.ToString();
            }
            return responseString;

        }
2、获取token
         /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        private async Task<string> Bearer_TokenPostAsync(string sSoUrlAddress,string userName,string userPassword)
        {
            string responseString = string.Empty;
            try
            {
                // 创建HttpWebRequest对象
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(sSoUrlAddress);
                _logger.Warn($"智慧系统Token地址:{sSoUrlAddress}");
                // 设置Post调⽤⽅法
                httpRequest.Method = "Post";
                //设置参数传输类型
                httpRequest.ContentType = " application/json; charset=utf-8";
                // 设置用户名和密码
                var usermesg = new UserMesgInput()
                {
                    Username = userName,
                    Password = userPassword,
                    UserDetail = true
                };
                string base64 = JsonConvert.SerializeObject(usermesg);
                //传输参数格式转换
                byte[] bytesRequestData = Encoding.UTF8.GetBytes(base64);
                //_logger.Warn($"入参数据格式转换:{bytesRequestData}");
                httpRequest.ContentLength = bytesRequestData.Length;

                Stream postStream = await httpRequest.GetRequestStreamAsync();
                postStream.Write(bytesRequestData, 0, bytesRequestData.Length);

                postStream.Close();
                //获取设置身份认证及请求超时时间
                SetWebRequest(httpRequest);
                _logger.Warn($"获取设置身份认证及请求超时时间");
                // HttpWebRequest发起调⽤
                using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse())
                {
                    _logger.Warn($"StreamReader对象");
                    // StreamReader对象
                    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                    //_logger.Warn($"返回结果{sr.ReadToEnd()}");
                    // 返回结果
                    responseString = sr.ReadToEnd();
                  
                    _logger.Warn($"调用智慧系统返回结果Token:{responseString}");
                    //return responseString;
                }
            }
            catch (Exception ex)
            {
                //返回错误信息
                responseString = ex.ToString();
            }
            return responseString;
        }
3、获取设置身份认证及请求超时时间
        /// <summary>
        /// 获取设置身份认证及请求超时时间
        /// </summary>
        /// <param name="request"></param>
        private static void SetWebRequest(HttpWebRequest request)
        {
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 1000000;

        }
4、在我使用的时候出现了下面的错误,通过查找是证书的问题,因为客户的web访问使用的IP地址访问,所以在代码中要加入跳过ssl验证的一行代码
System.Net.WebException: The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure.
posted @ 2024-03-18 21:42  悟自省  阅读(284)  评论(0编辑  收藏  举报