HttpWebRequest 二三事

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

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

 

[c-sharp] view plain copy print ?
 
  1. static   void  Main( string [] args)  
  2. {  
  3. for  ( int  i = 0; i < 10; i++)  
  4.     {  
  5.         Console.Write( "[{0}] Request - " , i + 1);  
  6.         TryGet( "https://login.live.com/" );  
  7.     }  
  8.     Console.Read();  
  9. }  
  10. static   void  TryGet( object  obj)  
  11. {  
  12. try   
  13.     {  
  14.         HttpWebRequest webReq =  null ;  
  15. string  url = ( string )obj;  
  16.         webReq = (HttpWebRequest)HttpWebRequest.Create(url);  
  17.         webReq.Timeout = 20 * 1000;  
  18.         var resp = webReq.GetResponse()  as  HttpWebResponse;  
  19.         resp.Close();  
  20.         Console.WriteLine( "Get Response StatusCode: {0}({1})" ,   
  21.             resp.StatusCode, ( int )resp.StatusCode);  
  22.     }  
  23. catch  (WebException we)  
  24.     {  
  25.         Console.WriteLine( "Get Response StatusCode: {0}({1})" ,  
  26.             we.Status, ( int )we.Status);  
  27.     }  
  28. catch  (Exception ex)  
  29.     {  
  30.         Console.WriteLine(ex);  
  31.     }  
  32. }  


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

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

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

[c-sharp] view plain copy print ?
 
  1. // 用多线程同时发出4个请求   
  2. WaitCallback methodTarget =  new  WaitCallback(TryGet);  
  3. ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  
  4. ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  
  5. ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  
  6. ThreadPool.QueueUserWorkItem(methodTarget,  "https://login.live.com/" );  

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

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

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

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

[c-sharp] view plain copy print ?
 
  1. <system.net>    
  2.   <connectionManagement>    
  3.   </connectionManagement>   
  4.   <defaultProxy>    
  5.     <proxy proxyaddress= "http://xxx.xxx.xxx.xxx:xxx"  bypassonlocal= "False" />    
  6.   </defaultProxy>   
  7.   <settings>    
  8.       <httpWebRequest useUnsafeHeaderParsing= "true" />   
  9.       <servicePointManager checkCertificateName= "true"      
  10.                            checkCertificateRevocationList= "true"       
  11.                            enableDnsRoundRobin= "true"      
  12.                            expect100Continue= "true"        
  13.                            useNagleAlgorithm= "true" />      
  14.   </settings>   
  15. </system.net>  

posted @ 2012-04-11 16:32  一修先生  阅读(12178)  评论(1编辑  收藏  举报