随着REST风格的流行,直接通过 HttpWebRequest 进行服务调用的客户端应用越来越多。这里总结一些可能需要费时调查的经验,希望能帮助大家。

1. 用完的HttpWebRequest要Abort()或者要把 Response.Close() 
否则会导致请求Timeout。 (HttpWebRequest.Method默认是GET)

static   void  Main( string [] args)  

{  

for  ( int  i = ; i < ; i++)  

    {  

        Console.Write( "[{0}] Request - " , i + );  

        TryGet( "https://login.live.com/" );  

    }  

    Console.Read();  

}  

static   void  TryGet( object  obj)  

{  

try   

    {  

        HttpWebRequest webReq =  null ;  

string  url = ( string )obj;  

        webReq = (HttpWebRequest)HttpWebRequest.Create(url);  

        webReq.Timeout =  * ;  

        var resp = webReq.GetResponse()  as  HttpWebResponse;  

        resp.Close();  

        Console.WriteLine( "Get Response StatusCode: {0}({1})" ,   

            resp.StatusCode, ( int )resp.StatusCode);  

    }  

catch  (WebException we)  

    {  

        Console.WriteLine( "Get Response StatusCode: {0}({1})" ,  

            we.Status, ( int )we.Status);  

    }  

catch  (Exception ex)  

    {  

        Console.WriteLine(ex);  

    }  

}  

上面的代码,会从第3次Request开始出现Timeout,因为GetResponse 后 Stream打开未关闭。 

解决方法:上面的代码中加上 resp.Close(); 或者 webReq.Abort(); 就能解决。

2. 多线程中调用 HttpWebRequest 时,需要设置 ServicePointManager.DefaultConnectionLimit 数(默认连接数是 2)。 
当多线程请求时,同时的连接数超过Limit时,GetResponse会抛出 Timeout WebException。

// 用多线程同时发出4个请求   

WaitCallback methodTarget =  new  WaitCallback(TryGet);  

ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  

ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  

ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  

ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  

解决方法:在GetResponse()之前设置 ServicePointManager.DefaultConnectionLimit = 100;

3.  当请求一个基于SSL的服务时,默认的验证行为都在 ServicePointManager 定义: 
ServicePointManager.CheckCertificateRevocationList = true;

如果请求的服务端证书没有第三方的认证支持,则请求会失败,如果要完全信任服务端证书,则可以将 
CheckCertificateRevocationList  设为 false。 

4. 可以在 <system.net> 配置节中配置 HttpWebRequest 的属性,包括 WebProxy

<system.net>
<connectionManagement> </connectionManagement> <defaultProxy> <proxy proxyaddress= "http://xxx.xxx.xxx.xxx:xxx" bypassonlocal= "False" /> </defaultProxy> <settings> <httpWebRequest useUnsafeHeaderParsing= "true" /> <servicePointManager checkCertificateName= "true" checkCertificateRevocationList= "true" enableDnsRoundRobin= "true" expect100Continue= "true" useNagleAlgorithm= "true" /> </settings> </system.net>

原文链接:https://www.cnblogs.com/1971ruru/archive/2012/04/11/2442589.html?tdsourcetag=s_pctim_aiomsg#

HttpWebRequest Timeout的更多相关文章

  1. HttpWebRequest的Timeout和ReadWriteTimeout

    HttpWebRequest.Timeout在发起请求开始,如果未从远程请求的URL得到任何数据的情况下,超过Timeout后,触发超时异常 HttpWebRequest.ReadWriteTimeo ...

  2. HttpWebRequest的timeout和ReadWriteTimeout(转载)

    公司[1]一牛人看我的代码,说我设置的timeout有误,还应该设置ReadWriteTimeout.本人很不服,于是上网查看了相关说明. HttpWebRequest httpWebRequest ...

  3. 通过WebClient/HttpWebRequest实现http的post/get方法

    ///<summary>/// 通过WebClient类Post数据到远程地址,需要Basic认证: /// 调用端自己处理异常 ///</summary>///<par ...

  4. C# post请求 HttpWebRequest

    //body是要传递的参数,格式"roleId=1&uid=2" //post的cotentType填写: //"application/x-www-form-u ...

  5. HttpWebRequest和WebClient的区别

     HttpWebRequest和WebClient的区别(From Linzheng): 1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Creat ...

  6. HttpWebRequest 请求带OAuth2 授权的webapi

    OAuth 2.0注意事项: 1. 获取access_token时,请使用POST private static string GetAuthorization(string username, st ...

  7. C#中HttpWebRequest的用法详解

    原文链接:http://www.cnblogs.com/love201314/p/5029312.html 1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数 ...

  8. HttpWebRequest.ReadWriteTimeout 属性

    获取或设置写入或读取流时的超时. 属性值在写入超时或读取超时之前的毫秒数.默认值为 300,000 毫秒(5 分钟). 备注 在写入由 GetRequestStream 方法返回的流时,或在读取由 G ...

  9. C#中HttpWebRequest的用法详解(转载)

    1.HttpWebRequest和HttpWebResponse类是用于发送和接收HTTP数据的最好选择.2.命名空间:System.Net3.HttpWebRequest对象不是利用new关键字创建 ...

随机推荐

  1. Python——迭代器&可迭代对象

    可迭代对象 什么是对象: Python中,一切皆对象.一个变量,一个列表,一个字符串,文件句柄,函数等等都可称为一个对象.一个对象就是一个实例,就是实实在在的东西. 什么是迭代 迭代就是一个重复的过程 ...

  2. IIS-This configuration section cannot be used at this path.

    Q:在IIS上部署web后,游览器打开报以下异常: This configuration section cannot be used at this path. This happens when ...

  3. Linux在丢失的情况下重置密码

    1.开机菜单是 移动光标到第一行 --敲击e 2.找到UTF-8,加上空格rd.break,敲击ctrl+x 3.输入以下命令 mount -o remount,rw /sysroot chroot ...

  4. HTML&CSS基础-前端免费开发工具Hbuilder介绍

    HTML&CSS基础-前端免费开发工具Hbuilder介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 工欲善其事必先利其器,想要干好活得有一个好的工具. 一.文本编辑工 ...

  5. word标题和序号列表的使用

  6. test20190818 NOIP2019 模拟赛

    0+0+20=20,不给大样例,小数据又水,还没有题解的垃圾题. A 题 问题描述: long long ago, Lxhgww 统治的国家里有 n 个城市,其中某一个城市是 capital (首都) ...

  7. memset()函数的使用

    1.概述 memset()函数,称为按字节赋值函数,使用时需要加头文件 #include<cstring>或者#include<string.h>.通常有两个用法: (1)用来 ...

  8. C语言蓝桥杯比赛原题和解析

    蓝桥杯:在计算机编程领域,是具有一定含金量的竞赛,用于选拔信息技术人才. 一般分为多个领域,其中包含了C/C#/C++/Java/Python等编程语言的测试题,多为算法的设计题. 下面,在搜题过程中 ...

  9. [RxJS] Groupby operator

    The use case is similar to Twitter "like" button, you can click "click" button o ...

  10. sort函数使用自定义数据排序使用

    package main import ( "fmt" "sort" ) type ServerSlice []Server type Server struc ...