HttpRequest重写,解决资源战胜/链接超时/分块下载事件通知 问题。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MyApi
{
    public class HttpRequest
    {
        public HttpRequest()
        {
            //string Url = "http://localhost:5192/api/Cab/5";
            //string httpMethod = "PUT";
            //string httpContent = "{‘Name‘: ‘B90‘, ‘Color‘: ‘Green‘, ‘Height‘: 1590, ‘Width‘: 4500 }";
            //Encoding httpCode = Encoding.Default;
            //Console.WriteLine(Get(Url, httpMethod, httpContent, httpCode));

            setEncoding = Encoding.Default;
        }

        public HttpRequest(string url, string method) : base()
        {
            setUrl = url;
            setMethod = method;
        }

        /// <summary>
        /// 服务请求地址 http://www.aaa.com/
        /// </summary>
        public string setUrl { get; set; }
        /// <summary>
        /// 服务请求方法:GET/POST/PUT/DELETE
        /// </summary>
        public string setMethod { get; set; }

        /// <summary>
        /// 设置服务请求数据类型
        /// </summary>
        [DefaultValue("text/html")]
        public string setContentType { get; set; }

        /// <summary>
        /// 设置服务页面编码
        /// </summary>
        public Encoding setEncoding { get; set; }

        public delegate void DownloadStartDelegate(int httpStatusCode);
        public delegate void DownloadProcessDelegate(long totalLength, long DownloadedByte, float percent);
        public delegate void DownloadEndDelegate(long totalLength);

        public event DownloadStartDelegate DownloadStart;
        public event DownloadProcessDelegate DownloadProcess;
        public event DownloadEndDelegate DownloadEnd;

        public string Get()
        {
            return Get(setUrl);
        }

        public string Get(string setUrl)
        {
            return Get(setUrl, "GET", null, setEncoding);
        }

        public string Get(string setUrl, string httpContent)
        {
            return Get(setUrl, "POSE", httpContent, setEncoding);
        }

        public string Get(string Url, string httpMethod, string httpContent, Encoding httpCode)
        {
            if (string.IsNullOrWhiteSpace(Url) || string.IsNullOrWhiteSpace(httpMethod))
            {
                throw new ArgumentException("Url or HttpMethod 参数不能为空!");
            }

            GC.Collect();
            StringBuilder content = new StringBuilder();
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamWriter sw = null;
            try
            {
                ServicePointManager.DefaultConnectionLimit = 512;
                request = WebRequest.Create(Url) as HttpWebRequest;
                request.Method = httpMethod;
                request.AllowAutoRedirect = true;
                request.KeepAlive = false;
                request.Accept = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)";
                request.ContentType = setContentType; //"application/octet-stream";
                request.Proxy = null;

                if (httpContent != null && !string.IsNullOrWhiteSpace(httpContent))
                {
                    using (sw = new StreamWriter(request.GetRequestStream()))
                    {
                        sw.Write(httpContent);
                    }
                }

                using (response = request.GetResponse() as HttpWebResponse)
                {
                    if (this.DownloadStart != null)
                        this.DownloadStart((int)response.StatusCode);

                    Stream stream = response.GetResponseStream();
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                        stream = new GZipStream(stream, CompressionMode.Decompress);

                    float percent = 0;
                    long totalDownloadedByte = 0;
                    long totalBytes = response.ContentLength;
                    while (stream.CanRead)
                    {
                        byte[] buffer = new byte[1024];
                        int canrds = stream.Read(buffer, 0, 1024);
                        totalDownloadedByte = canrds + totalDownloadedByte;
                        percent = (float)totalDownloadedByte / (float)totalBytes * 100;

                        if (DownloadProcess != null)
                            DownloadProcess(totalBytes, totalDownloadedByte, percent);

                        if (canrds == 0)
                            break;

                        content.Append(httpCode.GetString(buffer));
                    }
                    if (DownloadEnd != null)
                        DownloadEnd(totalBytes);
                    stream.Dispose();
                }
            }
            finally
            {
                if(request != null) request.Abort();
                if(response != null) response.Dispose();
                if(sw != null) sw.Dispose();
            }
            GC.SuppressFinalize(this);
            return content.ToString();

            /*
            Response.Write(Guid.NewGuid().ToString() + "<hr />");
            Response.Write(Guid.NewGuid().ToString("N") + "<hr />");

            Response.Write(GetHttpContent);
            Response.End();
            */
        }

    }
}
时间: 2024-10-14 04:10:23

HttpRequest重写,解决资源战胜/链接超时/分块下载事件通知 问题。的相关文章

对Azure二次开发,解决资源&ldquo;独占访问&rdquo;的问题

对Azure二次开发,解决资源"独占访问"的问题 在对Azure 进行二次开发过程中,首当其冲就是明白Azure的具体的"交互逻辑","消息机制","数据管理",在说问题前,我想你对于Rest API 的使用,至少有了初步的了解.这里,我就不多说,微软给我最巨大的印象就是它的文档,如果,你还有些不了解,请参考"Microsoft Developer Network"的"服务管理Rest API参考

战狼2百度云资源Mp4观看【Mp4/2.5G国语BD】战狼2云盘链接迅雷BT下载edk

<战狼2电影>高清完整版点击观看>>http://kanayi.cn<<点击观看 <三生三世电影>高清完整版点击观看>>http://kanayi.cn<<点击观看 战狼2百度云资源Mp4观看[Mp4/1.32G国语BD]战狼2云盘链接迅雷BT下载edk分谨慎的人,既然见到这个有可能克制魂魔的诅咒,自然仔细研究了一番,本想着有朝一日碰到这个诅咒可以破除,不过他自己都没想到,破除的方法没用上,反而是把这诅咒用上了.    而倒霉的被这个

解决远程桌面链接时出现"The RPC server is unavailable."或"RPC服务器不可用"的问题

解决远程桌面链接时出现"The RPC server is unavailable."或"RPC服务器不可用"的问题 解决远程桌面链接时出现"The RPC server is unavailable."或"RPC服务器不可用"的问题 有时候当用远程桌面链接某台Windows主机的时候会出现"The RPC server is unavailable."的问题,并在日志里还会看到如下图所示的错误: RPC 

微信端解决a标签链接 失效的问题

最近常碰到这个问题就是 在微信端点击a标签链接的时候,第一次正常界面跳转.但是,界面重新跳转回来再次点击a标签的话 .出现 界面不跳转,但是进度条加载完毕,点击多次页面无法跳转. 解决办法 在链接后边加上随机的参数(我这边加载的是时间戳): 比如说 $td参数 在控制器里面生成 部分安卓手机测试没发现之前的问题!!!!! iPhone手机部分检测也咩问题!!!!!!

oracle用plsql登陆出错,提示ORA-12170:TNS:链接超时 --------关闭防火墙试试

oracle用plsql登陆出错,提示ORA-12170:TNS:链接超时 但是使用sqlplus可以连接 ping 本机127.0.0.1 显示一般故障 后关闭防火墙,问题解决.

ecshop 完美解决动态ip登录超时和购物车清空问题

ecshop 完美解决动态ip登录超时和购物车清空问题 ECSHOP模板/ecshop开发中心(www.68ecshop.com) / 2014-05-06 前一段时间,ECSHOP开发中心的一个客户说自己的ecshop网店出了状况,就是有时候登录的时候会自动退出.而且购物车也没规律的会清空.刚开始一直找不到原因,到最后才知道了.他说的状况是由于像学校,公司一类的局域网.ip变化的原因造成的.ecshop存登录和购物车信息的时候用的是session,所以用cookie能够解决这个问题. 1.购物

java线程共享受限资源 解决资源竞争 thinking in java4 21.3

java线程共享受限资源 解决资源竞争  详细介绍请参阅:thinking in java4 21.3 thinking in java 4免费下载:http://download.csdn.net/detail/liangrui1988/7580155 package org.rui.thread.res; /** * 不正确的访问 资源 * @author lenovo * */ public abstract class IntGenerator { private volatile bo

解决本地软件链接不上虚拟机mysql 的问题:grant all privileges on *.* to &#39;root&#39;@&#39;%&#39; identified by &#39;nsfocus&#39;

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' ->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION; //本地操作的权限 mysql> GRANT ALL PRIVILEGES ON *.* TO ' root '@'%' ->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION; 首先要声明一下:一般情况下,修改MySQL

解决SecureCRT连接linux超时后断开[转]

方法一: 从客户端入手 方法二: 从服务端入手 修改/etc/ssh/sshd_config配置文件 ClientAliveInterval 300(默认为0) 这个参数的是意思是每5分钟,服务器向客户端发一个消息,用于保持连接 service sshd reload 生效 解决SecureCRT连接linux超时后断开[转]