using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Threading;

namespace US.Browser.IE.BLL
{
    public class USClientCommunicate
    {
        #region 向其他网站请求数据

        /// <summary>
        /// 读取返回的请求的数据 get
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetPage(string url)
        {
            try
            {
                HttpWebRequest webReques = (HttpWebRequest)HttpWebRequest.Create(url);//创建一个网站连接
                webReques.Method = "GET"; //get 方式获得
                HttpWebResponse webRespon = (HttpWebResponse)webReques.GetResponse();//获取网站放回的信息
                System.IO.Stream newstream = webRespon.GetResponseStream();//读取服务端响应的流
                System.IO.StreamReader srRead = new System.IO.StreamReader(newstream, System.Text.Encoding.UTF8);//将网页响应的流转化成utf-8数据
                string outString = srRead.ReadToEnd();//读取数据
                srRead.Close();//关闭
                return outString;//返回
            }
            catch { return ""; }
        }

        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="UUR"></param>
        /// <param name="UFN"></param>
        public static void DownloadFile(string UUR, string UFN)
        {
            try
            {
                System.Net.ServicePointManager.DefaultConnectionLimit = 100; System.GC.Collect();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UUR);
                request.Method = "get";//请求的类型 POST或者GET
                request.Headers.Add("Cache-Control", "no-cache");//设置无缓存
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获取返回的值
                Stream stream = response.GetResponseStream();
                Stream st = new FileStream(UFN, System.IO.FileMode.Create);
                byte[] by = new byte[102400]; int cn; while ((cn = stream.Read(by, 0, by.Length)) > 0) { st.Write(by, 0, cn); }
                st.Close(); stream.Close(); st.Dispose(); stream.Dispose(); request.Abort(); response.Close();
            }
            catch (Exception e) { }
            finally { }
        }

        public delegate void AsynPost();

        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="fun"></param>
        /// <param name="type"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string PostPage(string url, string method, System.Action<string> fun, string type, params string[] param)
        {
            try
            {
                method = method.ToUpper(); int i; string data = string.Empty; bool isPost = method == "POST"; fun = fun == null ? delegate(string e) { } : fun;
                for (i = 0; i < param.Length; i++) { param[i] = HttpUtility.UrlEncode(HttpUtility.UrlEncode(param[i], Encoding.UTF8).Replace("+", "%20")); }//获取参数
                if (param != null && param.Length != 0) { data = string.Join(",", param); } data = type + data; byte[] bytes = Encoding.UTF8.GetBytes(data);//生成传参
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //建立连接
                request.KeepAlive = false;//设置不长连接
                request.Timeout = 60000;//请求过期时间
                request.Method = method;//请求的类型 POST或者GET
                request.Headers.Add("Cache-Control", "no-cache");//设置无缓存
                request.ContentType = "application/x-www-form-urlencoded";//请求传参的类型 这里为FORM传参
                if (method == "POST") request.ContentLength = bytes.Length; request.Proxy = null;//请求的长度
                if (fun != null) //异步回调
                {
                    request.BeginGetRequestStream(new AsyncCallback(delegate(IAsyncResult result) //请求可写入数据
                    {
                        try
                        {
                            HttpWebRequest re = (HttpWebRequest)result.AsyncState;
                            if (method == "POST" && bytes.Length > 0)
                            {
                                using (Stream requestStream = request.EndGetRequestStream(result)) //写入数据
                                {
                                    requestStream.Write(bytes, 0, bytes.Length); requestStream.Close();
                                }
                            }
                            request.BeginGetResponse(new AsyncCallback(delegate(IAsyncResult res) { try { fun(ReadCallback((HttpWebRequest)res.AsyncState)); } catch (Exception e) { BLL.USIE.Exception(null, e); } }), request); ; //获取返回值
                        }
                        catch (Exception e) { BLL.USIE.Exception(null, e); }
                    }), request);
                }
                else
                {
                    if (isPost)
                    {
                        using (Stream requestStream = request.GetRequestStream())
                        {
                            requestStream.Write(bytes, 0, bytes.Length); requestStream.Close();
                        }
                    }
                    return ReadCallback(request);
                }
            }
            catch (Exception e) { BLL.USIE.Exception(null, e); }
            return "";
        }

        /// <summary>
        /// 异步处理
        /// </summary>
        /// <param name="asynchronousResult"></param>
        private static string ReadCallback(HttpWebRequest request)
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获取返回的值
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (Stream stream = response.GetResponseStream())
                {
                    System.IO.StreamReader srRead = new System.IO.StreamReader(stream, Encoding.UTF8);//将网页响应的流转化成utf-8数据
                    string _STR = srRead.ReadToEnd(); stream.Close(); request.Abort(); response.Close(); return _STR;
                }
            }
            return string.Empty;
        }

        #endregion
    }
}
