Adding Parameters to HttpClient Requests

1. Introduction

HttpClient is part of the Apache HttpComponents project that provides a toolset of low-level Java components focused on HTTP and associated protocols. The most essential function of HttpClient is to execute HTTP methods.

In this short tutorial, we’ll discuss adding parameters to HttpClient requests. We’ll learn how to use UriBuilder with String name-value pairs and also NameValuePairs. Similarly, we’ll see how to pass parameters using UrlEncodedFormEntity.

2. Add Parameters to HttpClient Requests Using UriBuilder

UriBuilder helps us to easily create URIs and add parameters via builder pattern. We can add parameters using String name-value pairs, or utilize NameValuePairs class for that purpose.

In this example, a final URL should look like this:

https://example.com?param1=value1¶m2=value2

Let’s see how to use String name-value pairs:

public CloseableHttpResponse sendHttpRequest() {
    HttpGet httpGet = new HttpGet("https://example.com");
    URI uri = new URIBuilder(httpGet.getURI())
      .addParameter("param1", "value1")
      .addParameter("param2", "value2")
      .build();
   ((HttpRequestBase) httpGet).setURI(uri);
    CloseableHttpResponse response = client.execute(httpGet);
    client.close();
}

Also, we can go with the NameValuePair list for HttpClient request:

public CloseableHttpResponse sendHttpRequest() {
    List nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
    nameValuePairs.add(new BasicNameValuePair("param2", "value2"));
    HttpGet httpGet = new HttpGet("https://example.com");
    URI uri = new URIBuilder(httpGet.getURI())
      .addParameters(nameValuePairs)
      .build();
   ((HttpRequestBase) httpGet).setURI(uri);
    CloseableHttpResponse response = client.execute(httpGet);
    client.close();
}

Similarly, UriBuilder can be used to add parameters to other HttpClient request methods.

3. Add Parameters to HttpClient Request Using UrlEncodedFormEntity

Another approach would be to utilize UrlEncodedFormEntity:

public CloseableHttpResponse sendHttpRequest() {
    List nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
    nameValuePairs.add(new BasicNameValuePair("param2", "value2"));
    HttpPost httpPost = new HttpPost("https://example.com");
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8));
    CloseableHttpResponse response = client.execute(httpPost);
    client.close();
}

Notice that UrlEncodedFormEntity couldn’t be used for GET requests, since GET request does not have a body that could contain an entity.

4. Conclusion

In this example, we showed how to add parameters to HttpClient requests. Also, the implementation of all these examples and code snippets are available over on GitHub.

Related posts: