using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Routing;
using System.Security.Cryptography;
using System.Web;
using System.Reflection;
using System.Collections.Specialized;

namespace Common
{
    public static class HttpWebRequestHelper
    {
        /// <summary>
        /// Get数据接口
        /// </summary>
        /// <param name="url">接口地址（带参数）</param>
        /// <returns></returns>
        public static string GetWebRequest(string url)
        {
            string responseContent = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //在这里对接收到的页面内容进行处理
            using (Stream resStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
                {
                    responseContent = reader.ReadToEnd();
                }
            }
            return responseContent;
        }
        public static string PutWebRequest(string url, string postData)
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "PUT";
            //req.Timeout = 10000;//设置请求超时时间，单位为毫秒
            req.ContentType = "application/json";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            using (Stream stream = resp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();//获取响应内容
                }
            }
            return result;
        }
        /// <summary>
        /// post数据接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="method">post和put，默认post</param>
        /// <returns></returns>
        public static string PostWebRequest(string url, string postData)
        {
            if (url.ToLower().StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;//设置这个安全协议必须在创建请求之前！
            }
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            //req.Timeout = 10000;//设置请求超时时间，单位为毫秒
            req.ContentType = "application/json";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            using (Stream stream = resp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();//获取响应内容
                }
            }
            return result;
        }
        /// <summary>
        /// post数据接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headerAuthorization"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostWebRequest(string url, string headerAuthorization, string postData)
        {
            if (url.ToLower().StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;//设置这个安全协议必须在创建请求之前！
            }
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add("Authorization", headerAuthorization);
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            using (Stream stream = resp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();//获取响应内容
                }
            }
            return result;
        }
        /// <summary>
        /// post数据接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headerAuthorization"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostAliOpenApi(string url, string headerAuthorization, string postData)
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Host = "openapi.aligenie.com";
            req.Headers.Add("Authorization", headerAuthorization);
            req.Headers.Add("x-acs-action", "ImportHotelConfig");
            req.Headers.Add("x-acs-version", "ip_1.0");
            req.Headers.Add("x-acs-date", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ"));
            req.Headers.Add("x-acs-signature-nonce", "bf0a025c-8b91-4f46-9a95-8a15421223a016891516640081");
            //req.Headers.Add("x-acs-content-sha256", "fdbc85c3630ae25fd7724f95d3b0029021a6433783226b90af76670e72cc4b23");
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            using (Stream stream = resp.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();//获取响应内容
                }
            }
            return result;
        }
        /// <summary>
        /// 获取阿里云签名结果串
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="accessKeySecret"></param>
        /// <returns></returns>
        public static string GetAliyunSignature(RouteValueDictionary dic, string accessKeySecret)
        {
            var canonicalizedQueryString = string.Join("&",
                dic.OrderBy(x => x.Key)
                .Select(x => PercentEncode(x.Key) + "=" + PercentEncode(x.Value.ToString())));
            var stringToSign = "GET&%2F&" + PercentEncode(canonicalizedQueryString);
            var keyBytes = Encoding.UTF8.GetBytes(accessKeySecret + "&");
            var hmac = new HMACSHA1(keyBytes);
            var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            return Convert.ToBase64String(hashBytes);
        }
        /// <summary>
        /// freego签名
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="accessKeySecret"></param>
        /// <returns></returns>
        public static string GetFreeGoSignature(RouteValueDictionary dic, string accessKeySecret)
        {
            var canonicalizedQueryString = string.Join("&", dic.OrderBy(x => x.Key)
                .Select(x => PercentEncode(x.Key) + "=" + PercentEncode(x.Value.ToString())));
            canonicalizedQueryString += "&key=" + accessKeySecret;
            return Tools.MD5Encrypt(canonicalizedQueryString);
        }
        private static string PercentEncode(string value)
        {
            return UpperCaseUrlEncode(value)
                .Replace("+", "%20")
                .Replace("*", "%2A")
                .Replace("%7E", "~");
        }

        private static string UpperCaseUrlEncode(string s)
        {
            char[] temp = HttpUtility.UrlEncode(s).ToCharArray();
            for (int i = 0; i < temp.Length - 2; i++)
            {
                if (temp[i] == '%')
                {
                    temp[i + 1] = char.ToUpper(temp[i + 1]);
                    temp[i + 2] = char.ToUpper(temp[i + 2]);
                }
            }
            return new string(temp);
        }

    }
}
