How to send http request using apache httpcomponents library

There are many ways to send request to a server and one of them is by using http client library. But this library has 2 versions now. The old httpclient and this httpcomponents. We will provide a sample code to try the latter.

But before that we need to add maven dependency to our project, this is assuming you are working on a maven project.

<!-- -->

A method that sends post request with variables:

public static String postRequest(String url, Map<String, String> params) throws IOException {
 log.debug("sending POST request to={}, params={}", url, params);

 try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  List<NameValuePair> postParameters = new ArrayList<>();

  // add post parameters
  params.forEach((key, value) -> {
   postParameters.add(new BasicNameValuePair(key, value));

  // initialize the post request
  HttpPost httpPost = new HttpPost(url);
  httpPost.setEntity(new UrlEncodedFormEntity(postParameters));

  StringBuilder responseString = new StringBuilder();

  // execute the request
  HttpResponse response = httpClient.execute(httpPost);

  // read the response
  if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
   HttpEntity responseHttpEntity = response.getEntity();
   InputStream content = responseHttpEntity.getContent();

   BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
   String line;
   while ((line = buffer.readLine()) != null) {

   // release all resources held by the responseHttpEntity

   log.debug("html-------\r\n" + responseString);

   return responseString.toString();
  } else {
   log.error("Error sending request with status=" + response.getStatusLine().getStatusCode());


 return "";

And finally a sample method call:

public Map<String, String> params= new HashMap<>();
params.put("param1", "value1");
params.put("param2", "value2");
params.put("param3", "value3");

MyClass.postRequest(AppSettings.MEMBER_NAME_URL, params);
How to send http request using apache httpcomponents library How to send http request using apache httpcomponents library Reviewed by Edward Legaspi on Monday, December 26, 2016 Rating: 5

No comments:

Powered by Blogger.