Search code examples
httprequesthttpclientapache-commons-httpclienthttp-host

HttpClient - When to use HttpHost parameter when executing HttpRequest


When using the following code:

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

When is it a good practice to use

httpClient.execute(httpHost, httpRequest);

Because httpHost's host can be determined by HttpRequest which includes the URL

/**
 * 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)

Is there any benefit over calling

httpClient.execute(httpRequest);

Is it proxy/firewall/balancer related solution? When host will be different than URL's host?


Solution

  • From the docs,

    Implementations may accept null if they can still determine a route, for example to a default target or by inspecting the request.

    Your question

    httpHost's host can be determined by HttpRequest which includes the URL

    just paraphrases what is written in the docs.

    There is no benefit of calling one over the other in your case. But, for advanced configurations, you can refer this where explicitly you may need to use HTTPHost. Hope this helps!