using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Configuration;

namespace ZXDT.CallCenter.MVCWeb.Commons
{
    public  class HttpHelper
    {
        //获取配置文件中api借口IP信息
        /// <summary>
        /// 通过get获取数据
        /// </summary>
        /// <param name="controllerName">/控制器名称/Action名称</param>
        /// <param name="filters">查询条件字符串</param>
        /// <returns></returns>
        public static string HttpGet(string controllerActionName,string filters)
        {
            //访问路径
            string httpUrl =  controllerActionName + (string.IsNullOrEmpty(filters.Trim()) ? "" : "?") + filters;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);

            request.KeepAlive = false;
            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("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        //获取配置文件中api借口IP信息
        /// <summary>
        /// 通过get获取数据
        /// </summary>
        /// <param name="controllerName">/控制器名称/Action名称</param>
        /// <param name="filters">查询条件字符串</param>
        /// <returns></returns>
        public static string HttpSMSSend(string httpUrl)
        {
           
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);

            request.KeepAlive = false;
            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("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        public static string HttpPost(string controllerActionName, object json)
        {
            string result = string.Empty;
            try
            {
                HttpClient client = new HttpClient();
                string httpUrl =  controllerActionName;
         
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = client.PostAsJsonAsync(httpUrl, json).Result;
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result; 
                    //response.Content.ReadAsAsync<Object>().Result.ToString();
                }
                else
                {
                    result = response.ReasonPhrase;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return result;
        }

        public static string HttpGet(string url)
        {
            string result = string.Empty;
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var task = client.GetAsync(new Uri(url)).Result;
                if (task.IsSuccessStatusCode)
                {
                    result = task.Content.ReadAsAsync<Object>().Result.ToString();
                }
                else
                {
                    result = task.ReasonPhrase;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return result;
        }

     
        public static byte[] File2HttpBytes(string imagepath)
        {
            WebRequest webRequest = WebRequest.Create(imagepath);
            WebResponse webResponse = webRequest.GetResponse();
            Stream stream = webResponse.GetResponseStream();
            MemoryStream mem = new MemoryStream();
            BufferedStream bfs = new BufferedStream(stream);
            int len = 0;
            byte[] buffer = new byte[4096];
            do
            {
                len = bfs.Read(buffer, 0, buffer.Length);
                if (len > 0)
                    mem.Write(buffer, 0, len);
            }
            while (len > 0);
            bfs.Close();
            byte[] picbytes = mem.ToArray();
            mem.Close();
            return picbytes;
        }

        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public static byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }

            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];

            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return buff;
        }


        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string DZ_MD5(string str)
        {
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("X").PadLeft(2, '0');
            return ret;
        }
    }
}
