Search in sources :

Example 41 with BasicHttpContext

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();
}
Also used : BasicScheme(org.apache.http.impl.auth.BasicScheme) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLContext(javax.net.ssl.SSLContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) KeyStore(java.security.KeyStore) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) URI(java.net.URI) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HostnameVerifier(javax.net.ssl.HostnameVerifier) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) ConnectionConfig(org.apache.http.config.ConnectionConfig)

Example 42 with BasicHttpContext

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) SSLSecurityException(de.geeksfactory.opacclient.networking.SSLSecurityException) HttpResponse(org.apache.http.HttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

Example 43 with BasicHttpContext

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;
}
Also used : InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) NotReachableException(de.geeksfactory.opacclient.networking.NotReachableException) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) SSLSecurityException(de.geeksfactory.opacclient.networking.SSLSecurityException) HttpResponse(org.apache.http.HttpResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

Example 44 with BasicHttpContext

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;
    }
}
Also used : ResponseHeader(com.ingenico.connect.gateway.sdk.java.ResponseHeader) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) CommunicationException(com.ingenico.connect.gateway.sdk.java.CommunicationException) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) Response(com.ingenico.connect.gateway.sdk.java.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 45 with BasicHttpContext

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();
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) HttpResponse(org.apache.http.HttpResponse) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Test(org.junit.Test)

Aggregations

BasicHttpContext (org.apache.http.protocol.BasicHttpContext)60 HttpContext (org.apache.http.protocol.HttpContext)37 IOException (java.io.IOException)24 HttpResponse (org.apache.http.HttpResponse)21 HttpGet (org.apache.http.client.methods.HttpGet)19 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)14 HttpHost (org.apache.http.HttpHost)11 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)11 HttpEntity (org.apache.http.HttpEntity)10 HttpPost (org.apache.http.client.methods.HttpPost)10 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)10 Header (org.apache.http.Header)8 BasicScheme (org.apache.http.impl.auth.BasicScheme)8 InputStream (java.io.InputStream)7 AuthScope (org.apache.http.auth.AuthScope)7 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)7 URI (java.net.URI)6 ArrayList (java.util.ArrayList)6 GZIPInputStream (java.util.zip.GZIPInputStream)6 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)6