using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace BPASmartClient.Helper
{
    /// <summary>
    /// 该类实现客户端http 同步请求
    /// 支持环境 -.net4.0/-.net4.5
    /// 创建人：奉友福
    /// </summary>
    public class HttpRequestHelper
    {
        #region 私有变量
        #endregion

        #region 公用函数
        /// <summary>
        /// GET 同步请求
        /// 创建人：奉友福
        /// 创建时间：2020-11-19
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>超时时间设置，默认5秒</returns>
        public static string HttpGetRequest(string url, int _timeout = 2000)
        {
            string resultData = string.Empty;

            try
            {
                WebClient wc = new WebClient();
                byte[] bytes = wc.DownloadData(url);
                string s = Encoding.UTF8.GetString(bytes);
                return s;
            }
            catch (Exception e)
            {
                throw e;
            }
            return "";

            try
            {
                var getrequest = HttpRequest.GetInstance().CreateHttpRequest(url, "GET", _timeout);
                var getreponse = getrequest.GetResponse() as HttpWebResponse;
                resultData = HttpRequest.GetInstance().GetHttpResponse(getreponse, "GET");
            }
            catch (Exception)
            {
                throw;
            }
            return resultData;
        }
        /// <summary>
        /// POST 同步请求
        /// 创建人：奉友福
        /// 创建时间：2020-11-19
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="PostJsonData">请求数据</param>
        /// <returns></returns>
        public static string HttpPostRequest(string url, string PostJsonData, int _timeout = 2000)
        {
            string resultData = string.Empty;
            try
            {
                var postrequest = HttpRequest.GetInstance().CreateHttpRequest(url, "POST", _timeout, PostJsonData);
                var postreponse = postrequest.GetResponse() as HttpWebResponse;
                resultData = HttpRequest.GetInstance().GetHttpResponse(postreponse, "POST");
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return resultData;
        }

        public static string HttpDeleteRequest(string url, string PostJsonData, int _timeout = 10000)
        {
            string resultData = string.Empty;
            try
            {
                var deleteRequest = HttpRequest.CreateDeleteHttpRequest(url, PostJsonData, _timeout);
                var deleteReponse = deleteRequest.GetResponse() as HttpWebResponse;
                using (StreamReader reader = new StreamReader(deleteReponse.GetResponseStream(), Encoding.GetEncoding("UTF-8")))
                {
                    resultData = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
            }
            return resultData;
        }

        /// <summary>
        ///  GET 同步请求 
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="head">头</param>
        /// <param name="headInfo">内容</param>
        /// <returns></returns>
        public static string GetHttpGetResponseWithHead(string url, HttpRequestHeader head, string headInfo)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json;charset=UTF-8";
            request.Timeout = 6000;
            request.Headers.Set(head, headInfo);
            StreamReader sr = null;
            HttpWebResponse response = null;
            Stream stream = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                stream = response.GetResponseStream();
                sr = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                var resultData = sr.ReadToEnd();
                return resultData;
            }
            catch (Exception ex)
            {
                Console.WriteLine(url + " 访问失败:" + ex.Message);
                //return ex.Message;
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (sr != null)
                {
                    sr.Dispose();
                }
            }
            return null;
        }



        /// <summary>
        ///   Post请求带Token
        /// 2021-2-2 by dulf
        /// </summary>
        /// <param name="url"></param>
        /// <param name="head"></param>
        /// <param name="headInfo"></param>
        /// <param name="postParam"></param>
        /// <returns></returns>
        public static string HttpPostResponseWithHead(string url, HttpRequestHeader head, string headInfo, string postParam, int Timeout = 6000)
        {
            string resultData = string.Empty;
            try
            {
                var postrequest = WebRequest.Create(url) as HttpWebRequest;
                postrequest.Timeout = Timeout;
                postrequest.Method = "POST";
                postrequest.ContentType = "application/json;charset=UTF-8";
                postrequest.Headers.Set(head, headInfo);
                byte[] data = Encoding.UTF8.GetBytes(postParam);
                using (Stream reqStream = postrequest.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    var postreponse = postrequest.GetResponse() as HttpWebResponse;
                    resultData = HttpRequest.GetInstance().GetHttpResponse(postreponse, "POST");
                    reqStream.Close();
                }
                return resultData;
            }
            catch (Exception ex)
            {
                Console.Write("请求<HttpPostResponseWithHead>异常:" + ex.Message);
            }
            return "";
        }
        #endregion

    }
    /// <summary>
    /// HTTP请求类
    /// </summary>
    public class HttpRequest
    {
        #region 私有变量
        /// <summary>
        /// http请求超时时间设置
        /// 默认值：5秒
        /// </summary>
        private static int Timeout = 5000;
        #endregion

        #region 单例模式
        private static HttpRequest _HttpRequest = null;
        public static HttpRequest GetInstance()
        {
            if (_HttpRequest == null)
            {
                _HttpRequest = new HttpRequest();
            }
            return _HttpRequest;
        }
        private HttpRequest()
        {

        }
        #endregion

        #region 公用函数    
        /// <summary>
        /// 函数名称：创建http请求
        /// 创建人：奉友福
        /// 创建时间：2020-11-19
        /// 例如GET 请求：  地址 + "GET"
        /// 例如POST请求：  地址 + "POST" + JSON
        /// </summary>
        /// <param name="url">http请求地址</param>
        /// <param name="requestType">http请求方式：GET/POST</param>
        /// <param name="strjson">http请求附带数据</param>
        /// <returns></returns>
        public HttpWebRequest CreateHttpRequest(string url, string requestType, int _timeout = 5000, params object[] strjson)
        {
            HttpWebRequest request = null;
            const string get = "GET";
            const string post = "POST";
            Timeout = _timeout;
            if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
            {
                request = CreateGetHttpRequest(url);
            }
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                request = CreatePostHttpRequest(url, strjson[0].ToString());
            }
            return request;
        }
        /// <summary>
        /// http获取数据
        /// </summary>
        /// <param name="response"></param>
        /// <param name="requestType"></param>
        /// <returns></returns>
        public string GetHttpResponse(HttpWebResponse response, string requestType)
        {
            var resultData = string.Empty;
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length < 1)
                    encoding = "UTF-8";
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                resultData = reader.ReadToEnd();
            }
            return resultData;
        }
        #endregion

        #region 私有函数
        /// <summary>
        /// http+GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns>请求结果</returns>
        private static HttpWebRequest CreateGetHttpRequest(string url)
        {
            var getrequest = WebRequest.Create(url) as HttpWebRequest;
            getrequest.Method = "GET";
            getrequest.Timeout = Timeout;
            getrequest.ContentType = "application/json;charset=UTF-8";
            getrequest.Proxy = null;
            getrequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return getrequest;
        }
        /// <summary>
        ///  http+POST请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData"></param>
        /// <returns>请求结果</returns>
        private static HttpWebRequest CreatePostHttpRequest(string url, string postData)
        {
            var postrequest = WebRequest.Create(url) as HttpWebRequest;
            //postrequest.KeepAlive = false;
            postrequest.Timeout = Timeout;
            postrequest.Method = "POST";
            postrequest.ContentType = "application/json;charset=UTF-8";
            //postrequest.ContentLength = postData.Length;
            //postrequest.AllowWriteStreamBuffering = false;
            //StreamWriter writer = new StreamWriter(postrequest.GetRequestStream(), Encoding.UTF8);
            //writer.Write(postData);
            //writer.Flush();
            byte[] data = Encoding.UTF8.GetBytes(postData);
            using (Stream reqStream = postrequest.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            return postrequest;
        }

        public static HttpWebRequest CreateDeleteHttpRequest(string url, string postJson, int _timeout = 5000)
        {
            var deleteRequest = WebRequest.Create(url) as HttpWebRequest;
            deleteRequest.Timeout = _timeout;
            deleteRequest.Method = "DELETE";
            deleteRequest.ContentType = "application/json;charset=UTF-8";
            byte[] data = Encoding.UTF8.GetBytes(postJson);
            using (Stream reqStream = deleteRequest.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            return deleteRequest;
        }
        #endregion
    }
}
