2014-09-18 35 views
0

我注意到org.apache.http.client.HttpClient指定了一個採用目標主機和請求參數的execute方法。HttpClient如何執行處理超指定的路徑?

/** 
* Executes a request to the target using the default context. 
* 
* @param target the target host for the request. 
*     Implementations may accept <code>null</code> 
*     if they can still determine a route, for example 
*     to a default target or by inspecting the request. 
* @param request the request to execute 
* 
* @return the response to the request. This is always a final response, 
*   never an intermediate response with an 1xx status code. 
*   Whether redirects or authentication challenges will be returned 
*   or handled automatically depends on the implementation and 
*   configuration of this client. 
* @throws IOException in case of a problem or the connection was aborted 
* @throws ClientProtocolException in case of an http protocol error 
*/ 
HttpResponse execute(HttpHost target, HttpRequest request) 
    throws IOException, ClientProtocolException; 

我鑽研DefaultHttpClientDefaultRequestDirector源代碼,並且它變得顯而易見的是,更簡單的方法execute(HttpRequest request)分離請求轉換成HttpHost對象和一個HttpRequest對象和呼叫轉發到多個指定的方法(實際上,也接受HttpContext對象 - 但我現在不關心上下文)。

我的問題是,由於請求和主機都可以接受一個URI,最終的URI是如何確定的?他們都擁有絕對的URI嗎?如果他們衝突怎麼辦?他們都有部分路徑?

回答

1

HttpHost代表物理端點。它只包含URI的權威部分(方案,主機和端口)。它不包含路徑。請求URI表示潛在可能是虛擬的資源。不會有衝突。只有HttpHost沒有明確給出請求URI的授權部分被假定爲是物理端點

例如

HttpHost = http://www.google.com:-1 
Request URI = http://www.google.ch/stuff 

將導致以下消息組成

TCP

localhost:<random> -> www.google.com:80 

HTTP

GET /stuff HTTP/1.1 
Host: www.google.ch 

你可以看到這種行爲在AbstractHttpClient.determineTarget私人助手方法,它不顧URI 4.0和4.3.5剛剛提取的方案,主機和端口之間從根本上改變對不提供一個HttpHostexecute變種。將目標和請求組合到最終路由中的代碼更加複雜,但仔細閱讀HttpRoute,HttpRoutePlanner和HttpRequest impl方法都清楚地指向來自HTTP主機的hosthostTarget,以及路徑(和params和fragment)來自本地部分,它來自HttpRequest。

+0

感謝oleg。我曾希望是這樣,並且通過編輯中提到的相關的'Http ...'類來挖掘一點,我相當相信你的描述總是如此......至少對於DefaultHttpClient類。 – 2014-09-19 16:44:18