using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SLZ_4
{
    class HTTPCom
    {
        private static string BaseUri;
        private static string url;

        public delegate bool CallbackGet(HttpWebResponse response, int nType, long nLen);
        public delegate bool CallbackPost(StreamReader reader, long nLen);
        public delegate bool CallbackPut(StreamReader reader, int nType, long nLen);
        public void RestClient(string baseUri)
        {
            BaseUri = baseUri;
            string[] strArray = baseUri.Split(':');
            url = string.Format("{0}:{1}", strArray[0], strArray[1]);
        }

        #region Get请求
        public static bool Get(string uri, int nType, string strToken, CallbackGet callbackGet)
        {
            //先根据用户请求的uri构造请求地址
            // string serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            // if (nType == (int)DataStruct.HTTPTYPE.GETPIC)
            //{
            //   serviceUrl = string.Format("{0}/{1}", url, uri);
            //}
            //创建Web访问对  象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);

            myRequest.Headers.Add("Authorization", strToken);
            myRequest.KeepAlive = false;
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
            }
            catch (Exception)
            {
                return false;
                throw;
            }
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快            
            bool bRet = callbackGet(myResponse, nType, myResponse.ContentLength);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
            //bool bRet = DisplayGet(reader, nType);
            myResponse.Close();
            return bRet;
        }

        #endregion

        #region Post请求
        public static string Post(string data, string uri, CallbackPost callbackPost)
        {
            string serviceUrl = uri;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);

            myRequest.Method = "POST";
            //myRequest.ContentType = "text/plain";
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            myRequest.KeepAlive = false;
            myRequest.Timeout = 5000;   //超时时间1S
            //发送请求
            if (data.Length > 0)
            {
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
                myRequest.ContentLength = buf.Length;

                //发送请求
                try
                {
                    Stream stream = myRequest.GetRequestStream();
                    stream.Write(buf, 0, buf.Length);
                    stream.Close();
                }
                catch (Exception ex)
                {
                    FileLogger.Log("发送失败:" + ex.Message, LogLevel.ERROR);
                    return ex.Message;
                }
            }

            //获取接口返回值
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
            }
            catch (Exception ex)
            {
                if (ex != null)
                {
                    FileLogger.Log("接受失败:" + ex.Message, LogLevel.ERROR);
                    return ex.Message;
                }
                else
                {
                    return "";
                }
            }
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            if (callbackPost != null)
            {
                callbackPost(reader, myResponse.ContentLength);
            }
            string strRet = reader.ReadToEnd();
            reader.Close();
            myResponse.Close();

            return strRet;
        }
        #endregion

        #region Put请求
        public static bool Put(string data, string uri, int nType, string strToken, CallbackPut callbackPut)
        {
            //先根据用户请求的uri构造请求地址
            string serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            //创建Web访问对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
            //把用户传过来的数据转成“UTF-8”的字节流
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);

            myRequest.Method = "PUT";
            myRequest.ContentLength = buf.Length;
            myRequest.ContentType = "application/json";
            myRequest.MaximumAutomaticRedirections = 1;
            myRequest.AllowAutoRedirect = true;
            myRequest.Headers.Add("Authorization", strToken);
            myRequest.KeepAlive = false;
            //发送请求
            Stream stream = myRequest.GetRequestStream();
            stream.Write(buf, 0, buf.Length);
            stream.Close();

            //获取接口返回值
            //通过Web访问对象获取响应内容
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法

            bool bRet = callbackPut(reader, nType, myResponse.ContentLength);
            //string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            //reader.Close();
            myResponse.Close();
            return bRet;
        }
        #endregion
    }
}
