23 Aralık 2019 Pazartesi

HttpComponents HttpClients Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.apache.http.impl.client.HttpClients;
Bu sınıf sayesinde CloseableHttpClient yaratılır.  Bu sınıf ile gelen he şey senkron çalışır. Asenkron çalışmak için bir başka kütüphane olan HttpAsyncClients kullanılır

custom metodu
Eğer createDefault() metodu yerine özelleştirilmiş bir şey istiyorsak custom() metodu kullanılır. HttpClientBuilder nesnesi döndürür. Böylece özelleştirme yapılabilir.

createDefault metodu
Şöyle yaparız
CloseableHttpClient client = HttpClients.createDefault();
setConnectionManager metodu
Örnek
Şöyle yaparız
public static String trustedAllPost(final String url) {
  String result = null;
  try {
    // 1. Create SSLContextBuilder to trust in every host
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (chain, authType) -> true);
    // 2. Create a SSLConnectionSocketFactory to not verify any hostname
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
      new NoopHostnameVerifier());
    HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create()
      .setSSLSocketFactory(sslsf).build();
    // 3. Associate both configurations through HttpClientConnectionManager to the HTTP 
    // client
    try (CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
      .build()) {
      HttpPost method = new HttpPost(url);
      try (CloseableHttpResponse response = httpclient.execute(method)) {
        result = EntityUtils.toString(response.getEntity());
      }
    }
  } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException |
    IOException | ParseException e) {
    log.error(e.getMessage(), e);
  }
  return result;
}
setDefaultCredentialsProvider metodu
Örnek - username and password authentication
Şöyle yaparız
public static String getWithBasicAuth(String url, String user, String pass)
    throws URISyntaxException, IOException, ParseException {
  String result = null;
  URI uri = new URI(url);
  // 1. Create a Basic Credentials provider to authenticate the call
  BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
  AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort());
  credsProvider.setCredentials(authScope, new UsernamePasswordCredentials(user,
    pass.toCharArray()));
  // 2. Add the credentials to the HHTP Client to use it in the call
  try (CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider).build()) {
    HttpGet httpget = new HttpGet(url);
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
      result = EntityUtils.toString(response.getEntity());
    }
  } catch (IOException | ParseException e) {
    log.error(e.getMessage(), e);
  }
  return result;
} 

setDefaultCookieStore metodu
Örnek
Şöyle yaparız
private static CookieStore cookieStore = new BasicCookieStore();
private static CloseableHttpClient httpclient = HttpClients.custom()
  .setDefaultCookieStore(cookieStore).build();
  
public static String postWithCookieStore(String url, String jsonBody) {
  // 1. Create HTTP Method
  HttpPost httpPost = new HttpPost(url);
  // 2. Set payload and content-type
  if (jsonBody != null) {
    httpPost.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
  }
  String result = null;
  // 3. Create HTTP client
  try {
    // 4. Execute the method through the HTTP client
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
      // 5. Read Response
      result = EntityUtils.toString(response.getEntity());
      log.info("Status Code: " + response.getCode() + " " + response.getReasonPhrase());
    }
  } catch (IOException | ParseException e) {
    log.error(e.getMessage(), e);
  }
  return result;
}

Hiç yorum yok:

Yorum Gönder