Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 393 lines (361 sloc) 11.693 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Collections.Generic;


namespace ExportBlog
{
    public class WebUtility
    {
        #region private members
        HttpWebRequest request = null;
        HttpWebResponse response = null;

        Uri uri;
        Encoding encoding = Encoding.UTF8;
        int timeOut = 3000;
        CookieContainer cc = new CookieContainer();
        string referer;
        string contentType = "application/x-www-form-urlencoded";
        byte[] data;

        Stream stream = null;

        bool hasError = false;

        bool did = false;
        #endregion

        public delegate void WebCallback(string result);
        /// <summary>
        /// 回调函数(声明了回调函数则使用异步请求)
        /// </summary>
        public WebCallback Callback = null;

        public WebUtility()
        {
            uri = null;
        }
        public WebUtility(string url)
        {
            uri = new Uri(url);
        }

        #region 属性
        /// <summary>
        /// 设置要请求的URL
        /// </summary>
        public string URL
        {
            set { uri = new Uri(value); }
        }
        /// <summary>
        /// 指定编码方式(默认:GB2312)
        /// </summary>
        public Encoding Encode
        {
            set { encoding = value; }
        }
        /// <summary>
        /// 设置连接超时时间(ms)
        /// </summary>
        public int TimeOut
        {
            set { timeOut = value; }
        }
        /// <summary>
        /// 设置/获取CookieContainer
        /// </summary>
        public CookieContainer Cookies
        {
            get { return cc; }
            set { cc = value; }
        }
        /// <summary>
        /// 设置请求链接源
        /// </summary>
        public string Referer
        {
            set { referer = value; }
        }
        /// <summary>
        /// 设置请求的内容类型
        /// </summary>
        public string ContentType
        {
            set { contentType = value; }
        }
        /// <summary>
        /// 获取请求返回的cookies
        /// </summary>
        public CookieCollection GetCookies
        {
            get { return did ? cc.GetCookies(uri) : null; }
        }
        /// <summary>
        /// 获取请求返回的HTTP标头
        /// </summary>
        public WebHeaderCollection Headers
        {
            get { return did ? response.Headers : null; }
        }
        /// <summary>
        /// 是否发生错误
        /// </summary>
        public bool HasError
        {
            get { return hasError; }
        }

        #endregion

        #region 提供方法
        /// <summary>
        /// GET方式发送请求
        /// </summary>
        /// <returns></returns>
        public string Get()
        {
            string msg = Send();

            if (hasError) return msg;

            StreamReader reader = null;
            try
            {
                reader = new StreamReader(stream, encoding);
                msg = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                hasError = true;
                msg = ex.Message;
            }
            finally
            {
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                response.Close();
            }
            return msg;
        }
        /// <summary>
        /// 获取图片(GET)
        /// </summary>
        /// <returns></returns>
        public Image GetImage()
        {
            string msg = Send();

            if (hasError) return null;

            Bitmap bitMap = null;
            try
            {
                Image original = Image.FromStream(stream);
                bitMap = new Bitmap(original);
            }
            catch (Exception ex)
            {
                hasError = true;
                msg = ex.Message;
            }
            finally
            {
                if (stream != null) stream.Close();
                response.Close();
            }
            return bitMap;
        }
        /// <summary>
        /// POST方式发送请求
        /// </summary>
        /// <param name="data">待发送数据</param>
        /// <param name="encoded">是否已进行编码</param>
        /// <returns></returns>
        public string Post(string data, bool encoded)
        {
            if (encoded) this.data = encoding.GetBytes(data);
            else this.data = encoding.GetBytes(EncodeData(data));

            return Post(this.data);
        }
        public string Post(byte[] data)
        {
            this.data = data;

            string msg = Send("POST");

            if (hasError) return msg;

            StreamReader reader = null;
            try
            {
                reader = new StreamReader(stream, encoding);
                msg = reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                hasError = true;
                msg = ex.Message;
            }
            finally
            {
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                response.Close();
            }
            return msg;
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName">文件全路径</param>
        /// <returns>返回错误消息</returns>
        public string DownloadFile(string fileName)
        {
            string msg = Send();

            if (hasError) return msg;

            int len = Headers["Content-Length"] != null ? int.Parse(Headers["Content-Length"].ToString()) : 1024;
            List<byte> data = new List<byte>(len);
            try
            {
                int i = -1;
                while ((i = stream.ReadByte()) > -1)
                {
                    data.Add((byte)i);
                }
            }
            catch (Exception ex)
            {
                hasError = true;
                return ex.Message;
            }
            finally
            {
                stream.Close();
                response.Close();
            }
            if (data.Count == 0)
            {
                return "文件长度为0";
            }
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(data.ToArray());
                return string.Empty;
            }
            catch (Exception ex)
            {
                hasError = true;
                return ex.Message;
            }
            finally
            {
                bw.Close();
                fs.Close();
            }
        }
        #endregion

        #region 私有方法
        private string Send()
        {
            return Send("GET");
        }
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="method">请求方式(GET/POST)</param>
        private string Send(string method)
        {
            if (uri == null)
            {
                hasError = true;
                return "URI is null";
            }
            try
            {
                if (uri.ToString().ToLower().StartsWith("https"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
                }
                System.Net.ServicePointManager.Expect100Continue = false;

                request = (HttpWebRequest)WebRequest.Create(uri);

                if (referer != null)
                {
                    request.Referer = referer;
                }
                request.CookieContainer = cc;
                request.KeepAlive = true;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
                request.Timeout = timeOut;
                
                if (method.ToUpper() == "POST")
                {
                    request.Method = "POST";
                    request.ContentType = contentType;
                    request.ContentLength = data.Length;

                    Stream newStream = request.GetRequestStream();
                    newStream.Write(data, 0, data.Length);
                    newStream.Close();
                }
                if (Callback == null)
                {
                    response = (HttpWebResponse)request.GetResponse();
                    stream = response.GetResponseStream();

                    hasError = false;
                    did = true;
                    return "true";
                }
                else
                {//使用异步方式
                    request.BeginGetResponse(EndRequest, null);

                    hasError = true;
                    return "loading";
                }
            }
            catch (Exception ex)
            {
                if (stream != null) stream.Close();
                if (response != null) response.Close();
                hasError = true;
                return ex.Message;
            }
        }

        private void EndRequest(IAsyncResult result)
        {
            request = (HttpWebRequest)result.AsyncState;
            response = (HttpWebResponse)request.EndGetResponse(result);
            stream = response.GetResponseStream();

            using (StreamReader reader = new StreamReader(stream, this.encoding))
            {
                StringBuilder sb = new StringBuilder();

                int c = reader.Read();
                while (c > -1)
                {
                    sb.Append((char)c);
                    c = reader.Read();
                }
                reader.Close();
                if (Callback != null)
                {
                    Callback(sb.ToString().Trim());
                }
            }
            did = true;
        }
        private string EncodeData(string data)
        {
            StringBuilder sb = new StringBuilder();
            Char[] reserved = { '=', '&' };

            int i = 0, j;
            while (i < data.Length)
            {
                j = data.IndexOfAny(reserved, i);
                if (j == -1)
                {
                    sb.Append(System.Web.HttpUtility.UrlEncode(data.Substring(i, data.Length - i), encoding));
                    break;
                }
                sb.Append(System.Web.HttpUtility.UrlEncode(data.Substring(i, j - i), encoding));
                sb.Append(data.Substring(j, 1));
                i = j + 1;
            }
            return sb.ToString();
        }
        //https
        private bool CheckValidationResult(object sender,
            System.Security.Cryptography.X509Certificates.X509Certificate certificate,
            System.Security.Cryptography.X509Certificates.X509Chain chain,
            System.Net.Security.SslPolicyErrors errors)
        { // Always accept
            return true;
        }
        #endregion
    }
}
Something went wrong with that request. Please try again.