use of org.apache.http.protocol.BasicHttpContext in project knox by apache.
the class Hadoop method createClient.
private CloseableHttpClient createClient(ClientContext clientContext) throws GeneralSecurityException {
// SSL
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
TrustStrategy trustStrategy = null;
if (clientContext.connection().secure()) {
hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
} else {
trustStrategy = TrustSelfSignedStrategy.INSTANCE;
System.out.println("**************** WARNING ******************\n" + "This is an insecure client instance and may\n" + "leave the interactions subject to a man in\n" + "the middle attack. Please use the login()\n" + "method instead of loginInsecure() for any\n" + "sensitive or production usecases.\n" + "*******************************************");
}
KeyStore trustStore = getTrustStore();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, trustStrategy).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();
// Pool
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(clientContext.pool().maxTotal());
connectionManager.setDefaultMaxPerRoute(clientContext.pool().defaultMaxPerRoute());
ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(clientContext.connection().bufferSize()).build();
connectionManager.setDefaultConnectionConfig(connectionConfig);
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(clientContext.socket().keepalive()).setSoLinger(clientContext.socket().linger()).setSoReuseAddress(clientContext.socket().reuseAddress()).setSoTimeout(clientContext.socket().timeout()).setTcpNoDelay(clientContext.socket().tcpNoDelay()).build();
connectionManager.setDefaultSocketConfig(socketConfig);
// Auth
URI uri = URI.create(clientContext.url());
host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
CredentialsProvider credentialsProvider = null;
if (clientContext.username() != null && clientContext.password() != null) {
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(clientContext.username(), clientContext.password()));
AuthCache authCache = new BasicAuthCache();
BasicScheme authScheme = new BasicScheme();
authCache.put(host, authScheme);
context = new BasicHttpContext();
context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
}
return HttpClients.custom().setConnectionManager(connectionManager).setDefaultCredentialsProvider(credentialsProvider).build();
}
use of org.apache.http.protocol.BasicHttpContext in project opacclient by opacapp.
the class ApacheBaseApi method httpPost.
/**
* Perform a HTTP POST request to a given URL
*
* @param url URL to fetch
* @param data POST data to send
* @param encoding Expected encoding of the response body
* @param ignore_errors If true, status codes above 400 do not raise an exception
* @param cookieStore If set, the given cookieStore is used instead of the built-in one.
* @return Answer content
* @throws NotReachableException Thrown when server returns a HTTP status code greater or equal
* than 400.
*/
public String httpPost(String url, HttpEntity data, String encoding, boolean ignore_errors, CookieStore cookieStore) throws IOException {
HttpPost httppost = new HttpPost(cleanUrl(url));
httppost.setEntity(data);
httppost.setHeader("Accept", "*/*");
HttpResponse response;
String html;
try {
if (cookieStore != null) {
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
response = http_client.execute(httppost, localContext);
} else {
response = http_client.execute(httppost);
}
if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
throw new NotReachableException(response.getStatusLine().getReasonPhrase());
}
html = convertStreamToString(response.getEntity().getContent(), encoding);
HttpUtils.consume(response.getEntity());
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
logHttpError(e);
throw new SSLSecurityException(e.getMessage());
} catch (javax.net.ssl.SSLException e) {
// aborted/interrupted handshake/connection
if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) {
logHttpError(e);
throw new NotReachableException(e.getMessage());
} else {
logHttpError(e);
throw new SSLSecurityException(e.getMessage());
}
} catch (InterruptedIOException e) {
logHttpError(e);
throw new NotReachableException(e.getMessage());
} catch (UnknownHostException e) {
throw new NotReachableException(e.getMessage());
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
logHttpError(e);
throw new NotReachableException(e.getMessage());
} else {
throw e;
}
}
return html;
}
use of org.apache.http.protocol.BasicHttpContext in project opacclient by opacapp.
the class ApacheBaseApi method httpGet.
/**
* Perform a HTTP GET request to a given URL
*
* @param url URL to fetch
* @param encoding Expected encoding of the response body
* @param ignore_errors If true, status codes above 400 do not raise an exception
* @param cookieStore If set, the given cookieStore is used instead of the built-in one.
* @return Answer content
* @throws NotReachableException Thrown when server returns a HTTP status code greater or equal
* than 400.
*/
public String httpGet(String url, String encoding, boolean ignore_errors, CookieStore cookieStore) throws IOException {
HttpGet httpget = new HttpGet(cleanUrl(url));
HttpResponse response;
String html;
httpget.setHeader("Accept", "*/*");
try {
if (cookieStore != null) {
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
response = http_client.execute(httpget, localContext);
} else {
response = http_client.execute(httpget);
}
if (!ignore_errors && response.getStatusLine().getStatusCode() >= 400) {
HttpUtils.consume(response.getEntity());
throw new NotReachableException(response.getStatusLine().getReasonPhrase());
}
html = convertStreamToString(response.getEntity().getContent(), encoding);
HttpUtils.consume(response.getEntity());
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
logHttpError(e);
throw new SSLSecurityException(e.getMessage());
} catch (javax.net.ssl.SSLException e) {
// aborted/interrupted handshake/connection
if (e.getMessage().contains("timed out") || e.getMessage().contains("reset by")) {
logHttpError(e);
throw new NotReachableException(e.getMessage());
} else {
logHttpError(e);
throw new SSLSecurityException(e.getMessage());
}
} catch (InterruptedIOException e) {
logHttpError(e);
throw new NotReachableException(e.getMessage());
} catch (UnknownHostException e) {
throw new NotReachableException(e.getMessage());
} catch (IOException e) {
if (e.getMessage() != null && e.getMessage().contains("Request aborted")) {
logHttpError(e);
throw new NotReachableException(e.getMessage());
} else {
throw e;
}
}
return html;
}
use of org.apache.http.protocol.BasicHttpContext in project connect-sdk-java by Ingenico-ePayments.
the class DefaultConnection method executeRequest.
@SuppressWarnings("resource")
protected Response executeRequest(HttpUriRequest request) {
final String requestId = UUID.randomUUID().toString();
final long startTime = System.currentTimeMillis();
HttpContext context = new BasicHttpContext();
context.setAttribute(REQUEST_ID_ATTRIBUTE, requestId);
context.setAttribute(START_TIMME_ATTRIBUTE, startTime);
try {
CloseableHttpResponse httpResponse = httpClient.execute(request, context);
HttpEntity entity = httpResponse.getEntity();
try {
int statusCode = httpResponse.getStatusLine().getStatusCode();
String body = entity == null ? null : EntityUtils.toString(entity, CHARSET);
List<ResponseHeader> headers = getHeaders(httpResponse);
return new Response(statusCode, body, headers);
} finally {
/*
* Ensure that the entity content is fully consumed and the
* content stream, if exists, is closed so the connection can be
* reused. Do not close the httpResponse because that will
* prevent the connection from being reused.
*/
EntityUtils.consume(entity);
}
} catch (ClientProtocolException e) {
logError(requestId, e, startTime, communicatorLogger);
throw new CommunicationException(e);
} catch (IOException e) {
logError(requestId, e, startTime, communicatorLogger);
throw new CommunicationException(e);
} catch (RuntimeException e) {
logError(requestId, e, startTime, communicatorLogger);
throw e;
}
}
use of org.apache.http.protocol.BasicHttpContext in project tutorials by eugenp.
the class HttpAsyncClientLiveTest method whenUseCookiesWithHttpAsyncClient_thenCorrect.
@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
cookie.setDomain(COOKIE_DOMAIN);
cookie.setPath("/");
cookieStore.addCookie(cookie);
final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
client.start();
final HttpGet request = new HttpGet(HOST_WITH_COOKIE);
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
final Future<HttpResponse> future = client.execute(request, localContext, null);
final HttpResponse response = future.get();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
Aggregations