Post、Get请求

post、get请求方法

  /// <summary>
        /// Post、Get请求
        /// </summary>
        /// <param name="url">请求地址(http:localshost:8080)</param>
        /// <param name="method">请求方式(post、get)</param>
        /// <param name="bodys">post请求参数</param>
        /// <param name="querys">get请求蚕食</param>
        /// <param name="headers">请求头</param>
        /// <param name="contentType">编码方式(application/x-www-form-urlencoded)</param>
        /// <returns></returns>
        public static string HttpInvoker(string url, string method, string bodys, string querys, Dictionary<string, string> headers, string contentType)
        {
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (querys.Length < 0)
            {
                url = url + "?" + querys;
            }

            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method.ToUpper();

            foreach (var header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = contentType;
            if (bodys.Length < 0)
            {
                //添加post参数
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }
            Stream s = httpResponse.GetResponseStream();
            string result = string.Empty;
            using (StreamReader reader = new StreamReader(s, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
View Code
原文地址:https://www.cnblogs.com/ZJ199012/p/10476532.html