HTTP REST client avec Apache httpclient5

Maven httpclient5

<dependency>
	<groupId>org.apache.httpcomponents.client5</groupId>
	<artifactId>httpclient5</artifactId>
	<version>5.1.3</version>
</dependency>

Exemple Java avec Apache httpclient5

package httprestclient;

import java.io.IOException;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class HttpRestClientExample {

  public static void main(final String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://127.0.0.1:5500/");

    System.out.println("Requête : " + httpGet.getMethod() + " " + httpGet.getUri());

    String response = httpclient.execute(httpGet, HttpRestClientExample::handleResponse);
    System.out.println(response);

  }

  private static String handleResponse(ClassicHttpResponse response) throws IOException, ParseException {
    int status = response.getCode();
    if (status == HttpStatus.SC_SUCCESS) {
      HttpEntity entity = response.getEntity();
      return EntityUtils.toString(entity);
    } else {
      System.err.println("Impossible de récupérer les données");
      return null;
    }

  }

}

Commentaires