HttpClient-执行HttpRequest时何时使用HttpHost参数

时间:2019-01-02 05:19:27

标签: httprequest httpclient apache-commons-httpclient http-host

使用以下代码时:

URIBuilder uriBuilder = new URIBuilder(url);
HttpPost httpRequest= new HttpPost(uriBuilder.build());
HttpHost httpHost= new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());

什么时候使用是一种好习惯

httpClient.execute(httpHost, httpRequest);

因为httpHost的主机可以由包含URL的HttpRequest确定

/**
 * Executes HTTP request using the default context.
 *
 * @param target    the target host for the request.
 *                  Implementations may accept {@code null}
 *                  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)

与致电相比有什么好处

httpClient.execute(httpRequest);

是代理/防火墙/平衡器相关的解决方案吗?主机何时与URL主机不同?

1 个答案:

答案 0 :(得分:1)

从文档中

  

如果实施仍可以确定路线,则可以接受null,   例如通过检查请求 将其设置为默认目标或

您的问题

  

httpHost的主机可由HttpRequest确定,其中包括   网址

只是解释文档中写的内容。

在您的情况下,互相呼叫没有好处。但是,对于高级配置,您可以在明确需要使用HTTPHost的地方引用this。希望这会有所帮助!