using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;

namespace Performance.Infrastructure
{
    public class HttpHelper
    {
        #region 发送post请求

        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr, string encoding = "utf-8", bool IsJson = false)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            string retString = "";

            if (Url.ToLower().StartsWith("https"))
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证

            try
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                System.GC.Collect();
                request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
                if (IsJson)
                    request.ContentType = "application/json";
                else
                    request.ContentType = "application/x-www-form-urlencoded";
                byte[] bData = (Encoding.UTF8.GetBytes(postDataStr));
                request.ContentLength = bData.Length;
                Stream writeStream = request.GetRequestStream();
                writeStream.Write(bData, 0, bData.Length);
                writeStream.Close();

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(encoding));
                    retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();

                    return retString;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                    request.Abort();
                if (response != null)
                    response.Close();
            }
        }

        #endregion 发送post请求

        public static string HttpPost(string Url, string postDataStr, bool IsJson)
        {
            return HttpPost(Url, postDataStr, "utf-8", IsJson);
        }

        #region 发送get请求

        /// <summary>
        /// 发送get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr, string encoding = "utf-8")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(encoding));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        #endregion 发送get请求

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受
            return true;
        }


        #region 发送post请求

        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static void HttpPostNoRequest(string Url, string postDataStr, bool IsJson = false)
        {
            HttpWebResponse response = null;
            HttpWebRequest request = null;

            if (Url.ToLower().StartsWith("https"))
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证

            try
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                System.GC.Collect();
                request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version10;
                if (IsJson)
                    request.ContentType = "application/json";
                else
                    request.ContentType = "application/x-www-form-urlencoded";
                byte[] bData = (Encoding.UTF8.GetBytes(postDataStr));
                request.ContentLength = bData.Length;
                Stream writeStream = request.GetRequestStream();
                writeStream.Write(bData, 0, bData.Length);
                writeStream.Close();

                request.GetResponseAsync();
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (request != null)
                    request.Abort();
                if (response != null)
                    response.Close();
            }
        }

        #endregion 发送post请求

        /// <summary>
        /// 请求文件 post file
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="file">文件路径</param>
        /// <returns></returns>
        public static string HttpClient(string url, string file, bool IsAsync = false)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data
                client.QueryString["path"] = file;
                if (!IsAsync)
                {
                    byte[] fileb = client.UploadFile(new Uri(url), "POST", file);
                    string res = Encoding.UTF8.GetString(fileb);
                    return res;
                }
                else
                    client.UploadFileAsync(new Uri(url), "POST", file);
                return "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static string HttpPost(string url, int timeout = -1, Dictionary<string, string> files = null, Dictionary<string, string> parameters = null)
        {
            try
            {
                var client = new RestClient(url);
                client.Timeout = timeout;
                var request = new RestRequest(Method.POST);
                if (files != null && files.Any())
                {
                    foreach (var item in files)
                    {
                        request.AddFile(item.Key, item.Value);
                    }
                }
                if (parameters != null && parameters.Any())
                {
                    foreach (var item in parameters)
                    {
                        request.AddParameter(item.Key, item.Value);
                    }
                }
                IRestResponse response = client.Execute(request);
                return response.Content;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}