HttpWebRequest POST 请求API数据

根子 C# JSON 2021-11-02 19:03 原创 770

兼容https协议  建议.net framework4.6以上版本

        /// <summary>
        ///  HttpWebRequest请求API数据
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="jsonstr">参数</param>
        /// <param name="token">Bearer token 如有需要</param>
        /// <param name="success">返回状态 true or false</param>
        /// <param name="errormsg">返回错误消息</param>
        /// <returns>返回结果 string</returns>
        public string PostJsonData(string url, string jsonstr, string token, out bool success, out string errormsg)
        {
            GC.Collect();//垃圾回收,回收没有正常关闭的http连接
            success = true;
            errormsg = "";
            string result = "";

            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;

            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                }
                request = (HttpWebRequest)WebRequest.Create(url);

                request.Method = "POST";
                request.Timeout = int.MaxValue;
                if (!string.IsNullOrWhiteSpace(token))
                {
                    request.Headers.Add("Authorization", "Bearer " + token);
                }
                if (!string.IsNullOrWhiteSpace(jsonstr))
                {
                    byte[] btData = Encoding.UTF8.GetBytes(jsonstr);
                    request.ContentLength = btData.Length;
                    request.ContentType = "application/json";

                    //往服务器写入数据
                    reqStream = request.GetRequestStream();
                    reqStream.Write(btData, 0, btData.Length);
                    reqStream.Close();
                }
                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();

                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception ex)
            {
                success = false;
                errormsg = ex.Message.ToString();
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }


        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认,否则打不开    
            return true;
        }


留 言

木艮子の笔记