HttpClient學習研究---第四章:HTTP authenticationHTTP身份驗證
阿新 • • 發佈:2019-01-10
4.7.1. 4.7.1。NTLM connection persistenceNTLM連線永續性
The這個 NTLM
authentication scheme is significantly more expensive in terms of computational overhead and performance impact than the standard身份驗證方案是更昂貴的計算開銷和效能方面比標準的影響
Basic
and和 Digest
schemes.
方案。This is likely to be one of the main reasons why Microsoft chose to make
NTLM
authentication scheme stateful.
身份驗證方案狀態。That is, once authenticated, the user identity is associated with that connection for its entire life span.
也就是說,一旦使用者通過身份認證,身份是與之相關的連線對其整個生命週期。The stateful nature of有狀態的本質 NTLM
connections makes connection persistence more complex, as for the obvious reason persistent
NTLM
connections may not be re-used by users with a different user identity.
連線可能不被重用,使用者用一個不同的使用者身份。The standard connection managers shipped with HttpClient are fully capable of managing stateful connections.
附帶的標準連線經理HttpClient完全有能力管理有狀態連線。However, it is critically important that logically related requests within the same session use the same execution context in order to make them aware of the current user identity.
NTLM
protected
resources. 受保護的資源。For detailed discussion on stateful HTTP connections please refer to詳細的討論有狀態的HTTP連線請參考this這section.部分。
As作為 NTLM
connections are stateful it is generally recommended to trigger連線���態通常建議來觸發 NTLM
authentication
using a relatively cheap method, such as身份驗證使用相對便宜的方法,如 GET
or或 HEAD
, and re-use the same connection to execute more expensive
methods, especially those enclose a request entity, such as,和重用相同的連線來執行更多的昂貴的方法,尤其是那些附上一個請求的實體,如 POST
or或 PUT
.
CloseableHttpClient httpclient = <...> CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials("user", "pwd", "myworkstation", "microsoft.com")); HttpHost target = new HttpHost("www.microsoft.com", 80, "http"); // Make sure the same context is used to execute logically related requests HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); // Execute a cheap method first. This will trigger NTLM authentication HttpGet httpget = new HttpGet("/ntlm-protected/info"); CloseableHttpResponse response1 = httpclient.execute(target, httpget, context); try { HttpEntity entity1 = response1.getEntity(); } finally { response1.close(); } // Execute an expensive method next reusing the same context (and connection) HttpPost httppost = new HttpPost("/ntlm-protected/form"); httppost.setEntity(new StringEntity("lots and lots of data")); CloseableHttpResponse response2 = httpclient.execute(target, httppost, context); try { HttpEntity entity2 = response2.getEntity(); } finally { response2.close(); }