WebClient的超时问题及解决

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

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

        /// 
        /// 重写GetWebRequest,添加WebRequest对象超时时间
        /// 
        /// 
        /// 
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.Timeout = Timeout;
            request.ReadWriteTimeout = Timeout;
            return request;
        }
    }
 使用: 
  
        /// 
        /// 获取url 内容
        /// 
        /// 
        /// 
        /// 
        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);  
        }







你可能感兴趣的:(.net)