閱讀593 返回首頁    go 技術社區[雲棲]


《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(“https://localhost/1″);

httpget1.setConfig(requestConfig);

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

try {

HttpEntity entity1 = response1.getEntity();

} finally {

response1.close();

}

HttpGet httpget2 = new HttpGet(“https://localhost/2″);

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

try {

HttpEntity entity2 = response2.getEntity();

} finally {

response2.close();

}

 轉載自 並發編程網 - ifeve.com

最後更新:2017-05-19 12:04:55

  上一篇:go  CentOS 上最佳的第三方倉庫
  下一篇:go  如何在 Vim 中使用模式行進行文件特定的設置