首页 新闻 会员 周边

HttpWebRequest发送数据超时后修复处理

1
悬赏园豆:50 [已解决问题] 解决于 2012-03-14 12:44

    最近遇到一个问题请教下,在一个时间控件中写了一个HttpWebRequest以post的形式发送,设置了发送超时5秒,但当我网络不好断了一段时间网络,然后再连接上后,就不可以继续发送请求了,不知道有没有什么可以修复的方法和属性,下面是我的代码段

strParams = HttpUtility.UrlPathEncode(strParams);      

                byte[] byteRequest = Encoding.Default.GetBytes(strParams);//编码    

                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(consumer.ConsumerAddress.ToString().Trim())); 

                httpWebRequest.Credentials = CredentialCache.DefaultCredentials;                 httpWebRequest.ContentType = "application/x-www-form-urlencoded";//这一个参数似乎是必需的。

                httpWebRequest.Method = "POST";//这个是请求方法,必须是POST,这个可以通过分析实际登录的情况得到采用的方法      

                httpWebRequest.Timeout = consumer.ConsumerTimeOut;                 httpWebRequest.ContentLength = byteRequest.Length;//POST数据的长度,这个参数是必需的。              

                httpWebRequest.ProtocolVersion = HttpVersion.Version10;                 httpWebRequest.KeepAlive = false;                 //下面是发送数据到服务器           

                Stream stream = httpWebRequest.GetRequestStream();             

                stream.Write(byteRequest, 0, byteRequest.Length);                 stream.Close();                

                HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();//取服务器的响应            

                StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);

在最后一句会有异常

Vision Ma的主页 Vision Ma | 初学一级 | 园豆:81
提问于:2012-03-13 11:10
< >
分享
最佳答案
0

try this below please:

 1  public class Demo
2 {
3 ///<summary>
4 /// 失败次数计数
5 ///</summary>
6 private static int count = 0;
7
8 ///<summary>
9 /// MyPost
10 ///</summary>
11 ///<param name="url">请求地址</param>
12 ///<param name="paras">传递的参数</param>
13 ///<returns></returns>
14 public static string MyPost(string url, Dictionary<string, string> paras)
15 {
16 string rs = string.Empty;
17 if (count > 10) throw new Exception("重试次数超过十次。。。。。");
18 try
19 {
20 // your action here
21 }
22 catch
23 {
24 count++;
25 MyPost(url, paras);
26 }
27 count = 0;
28 return rs;
29 }
30 }
收获园豆:50
世界万物 | 菜鸟二级 |园豆:276 | 2012-03-13 18:26

赞~~

EApple | 园豆:139 (初学一级) | 2019-01-10 16:09

@EApple: 现在看看 有多线程的问题啊

世界万物 | 园豆:276 (菜鸟二级) | 2019-01-10 19:14

@世界万物: 有想到更好的处理方式嘛

EApple | 园豆:139 (初学一级) | 2019-01-11 14:07
其他回答(3)
0

可能是时间超时了。你把时间设置长一点。

悟行 | 园豆:12559 (专家六级) | 2012-03-13 11:35
0

你说的修复是把发送失败的数据重新发送一下吗?

如果不是的话  只要有个try catch就可以了啊

liulun | 园豆:257 (菜鸟二级) | 2012-03-13 16:16
0

试试:httpWebRequest.KeepAlive = true;

dudu | 园豆:31003 (高人七级) | 2012-03-13 17:48
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册