码迷,mamicode.com
首页 > Web开发 > 详细

WebClient的超时问题及解决

时间:2015-04-22 11:44:42      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Webclient在下载请求时无法设置请求超时时间和请求读写超时时间。WebClient在异步下载时遇到网络不通等问题时没有响应超时造成app挂起。
    public class WebClientto : WebClient
    {
        /// <summary>
        /// 过期时间
        /// </summary>
        public int Timeout { get; set; }

        public WebClientto(int timeout)
        {
            Timeout = timeout;
        }

        /// <summary>
        /// 重写GetWebRequest,添加WebRequest对象超时时间
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.Timeout = Timeout;
            request.ReadWriteTimeout = Timeout;
            return request;
        }
    }

使用:
        /// <summary>
        /// 获取url 内容
        /// </summary>
        /// <param name="url"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string getResponseByEncodeUrl(string url, string name)
        {
            WebClient client = new WebClientto(4500);  //设置4.5s超时时间
            byte[] reply = client.DownloadData(url + HttpUtility.UrlEncode(name, Encoding.GetEncoding("GBK")));
            if (reply == null || reply.Length == 0)
            {
                return "0";
            }
            return Encoding.UTF8.GetString(reply);  
        }







WebClient的超时问题及解决

标签:

原文地址:http://blog.csdn.net/ycwol/article/details/45190613

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!