HttpWebRequest设置timeout
作者:admin 来源:远程 2022/10/10 16:57:07

编写C#提交http数据的程序过程中,HttpWebRequest提交数据代码如下:

if (!string.IsNullOrEmpty(requestJson))
            {
                byte[] data = requestEncoding.GetBytes(requestJson);
                request.ContentLength = data.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
当目标网址不可访问时,程序将会在Stream stream = request.GetRequestStream()处卡死。此时我希望程序可以超时退出。

应如下设置:

if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
                request.ReadWriteTimeout = timeout.Value;
                request.KeepAlive = false;
            }
仅设置Timeout参数是不起作用的,需要设置ReadWriteTimeout参数。

称      呼:
联系方式:
您的评论:
技术支持:l.w.dong@qq.com www.luweidong.cn
广州市   wx:lwdred
Copyright © 2014 三味书屋 All Rights Reserved
技术支持:l.w.dong@qq.com  sitemap xml  sitemap html

粤公网安备44010602011869号

粤ICP备13031080号-1