no

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 ol...

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.

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.3.4</version>
</dependency>

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) {
    responseString.append(line);
   }

   // release all resources held by the responseHttpEntity
   EntityUtils.consume(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);

Related

java-library 4329745154686517180

Post a Comment Default Comments

item