using System.Net;
using System.Text;

namespace BPA.SAAS.Manage.Comm.Util
{
    public static class HttpHelper
    {
        private static readonly HttpClient client = new HttpClient();

        /// <summary>
        /// Get 请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <param name="headers"></param>
        /// <param name="platform"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string HttpGet(string url, string postDataStr, Dictionary<string, string> headers, string contentType = "")
        {
            var result = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + postDataStr);

            request.ServicePoint.Expect100Continue = false;   //加了这一行代码 就OK了
            request.Method = "GET";
            request.ContentType = contentType;
            foreach (KeyValuePair<string, string> kv in headers)
            {
                request.Headers.Add(kv.Key, kv.Value);
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            result = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return result;
        }


        public static string PostData(string url, string postData, Encoding encoding, string ContentType, Dictionary<string, string> headers)
        {

            HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);

            myReq.Method = "POST";
            myReq.Timeout = 600 * 60;
            byte[] byteArray = encoding.GetBytes(postData);
            myReq.ContentType = ContentType;
            //对键值对进行遍历
            foreach (KeyValuePair<string, string> kv in headers)
            {
                myReq.Headers.Add(kv.Key, kv.Value);
            }
            Stream dataStream = myReq.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
            dataStream = HttpWResp.GetResponseStream();
            string result = "";
            using (StreamReader myStreamReader = new StreamReader(dataStream, encoding))
            {
                result = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            dataStream.Close();
            HttpWResp.Close();
            return result;
        }
    }
}
