1. 程式人生 > >《HttpClient官方文件》1.3 HTTP執行上下文

《HttpClient官方文件》1.3 HTTP執行上下文

1.3 HTTP執行上下文

HTTP起初是被設計成一種無狀態的、面向請求和響應的協議。然而實際的應用經常需要在請求-響應切換過程中儲存狀態資訊。為了使應用能夠維持處理狀態,HttpClient允許HTTP請求可以在一個特殊的上下文環境(HttpContext)中執行。如果一個context在連續的HTTP請求中被複用,那麼這些邏輯相關的請求可以參與到同一個邏輯會話中。HttpContext功能與java.util.Map<String, Object>類似,它是一組任意值的集合。一個應用程式可以在請求執行之前填充上下文屬性或者在請求執行完成後檢查上下文。

HttpContext可以儲存多個物件,因而它在多個執行緒共享時可能並不安全。這裡推薦每個執行緒維持各自HttpContext。

在HTTP請求執行的過程中,HttpClient向context添加了以下屬性:

  • HttpConnection,表示與目標伺服器的實際連線
  • HttpHost,表示連線的目標
  • HttpRoute,表示完整的連線路由
  • HttpRequest,表示Http請求
  • HttpResponse,表示Http響應
  • lang.Boolean,表示請求是否被完整的傳送到目標
  • RequestConfig,表示請求的配置
  • java.util.List<URI>,表示在請求處理過程中接收到的一組重定向地址集合

可以使用HttpClientContext這個介面卡類來簡化操作上下文狀態。

HttpContext context = <…>

HttpClientContext clientContext = HttpClientContext.adapt(context);

HttpHost target = clientContext.getTargetHost();

HttpRequest request = clientContext.getRequest();

HttpResponse response = clientContext.getResponse();

RequestConfig config = clientContext.getRequestConfig();

處於同一個邏輯相關的會話中多個請求應該使用同一個HttpContext例項進行處理,以此來保證會話上下文和狀態資訊在請求之間自動傳播。

在下面的例子中,初始請求設定的配置資訊儲存在執行上下文中,並且傳播給其他共享同一個上下文的連續請求。

CloseableHttpClient httpclient = HttpClients.createDefault();

RequestConfig requestConfig = RequestConfig.custom()

.setSocketTimeout(1000)

.setConnectTimeout(1000)

.build();
HttpGet httpget1 = new HttpGet(“http://localhost/1”);

httpget1.setConfig(requestConfig);

CloseableHttpResponse response1 = httpclient.execute(httpget1, context);

try {

HttpEntity entity1 = response1.getEntity();

} finally {

response1.close();

}

HttpGet httpget2 = new HttpGet(“http://localhost/2”);

CloseableHttpResponse response2 = httpclient.execute(httpget2, context);

try {

HttpEntity entity2 = response2.getEntity();

} finally {

response2.close();

}