16 Mayıs 2023 Salı

HttpComponents HttpGet Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.http.client.methods.HttpGet;
constructor
Şöyle yaparız. Burada org.apache.http.util.EntityUtils kullanılıyor
void getFlight() throws Exception {
  HttpClient client = HttpClients.createDefault();
  HttpGet request = new HttpGet("https://www.cleartrip.com");
  HttpResponse response = client.execute(request);
  HttpEntity entity = response.getEntity();

  String responseBody = EntityUtils.toString(entity);
  int statusCode = response.getStatusLine().getStatusCode();
  System.out.println(statusCode);
  System.out.println(responseBody);
}
setHeader metodu
Örnek
Şöyle yaparız. Burada try block içinde kullanılıyor.
try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
  HttpGet httpGet = new HttpGet( url.toString() );
  httpGet.setHeader( "Authorization", String.format( "token %s", "<token>" ));
  httpGet.setHeader( "Accept", "application/vnd.github.v3.raw" );

  try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
     HttpEntity entity = httpResponse.getEntity();

    if (entity != null) {
       FileUtils.copyInputStreamToFile( entity.getContent(), file);
    }
  }
}
setHeaders metodu
Örnek
Şöyle yaparız
String sEndpoint = "https://mydomain.com:9090/sample";
Map<String, String> headers = new HashMap<>();
headers.put(HttpHeaders.AUTHORIZATION, BEARER_TOKEN);

String body = null;
HttpGet get = new HttpGet(sEndpoint);
get.setHeaders(headers.entrySet()alo
  .stream()
  .map(entry -> new BasicHeader(entry.getKey(), entry.getValue()))
  .toArray(Header[]::new));
try (CloseableHttpClient httpClient = ...;
     CloseableHttpResponse response = httpClient.execute(get)) {
  body = EntityUtils.toString(response.getEntity(), Charset.defaultCharset());
}


Hiç yorum yok:

Yorum Gönder