隨着REST風格的流行,直接通過 HttpWebRequest 進行服務調用的客戶端應用越來越多。這里總結一些可能需要費時調查的經驗,希望能幫助大家。
1. 用完的HttpWebRequest要Abort()或者要把 Response.Close()
否則會導致請求Timeout。 (HttpWebRequest.Method默認是GET)
static void Main( string [] args) { for ( int i = 0; i < 10; i++) { Console.Write( "[{0}] Request - " , i + 1); 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 = 20 * 1000; 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#