Search in sources :

Example 26 with HttpContext

use of org.apache.http.protocol.HttpContext in project tutorials by eugenp.

the class HttpClientConnectionManagementLiveTest method whenCustomizingKeepAliveStrategy_thenNoExceptions.

// 5
@Test
public final // 5.1
void whenCustomizingKeepAliveStrategy_thenNoExceptions() throws ClientProtocolException, IOException {
    final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {

        @Override
        public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
            final HeaderElementIterator it = new BasicHeaderElementIterator(myResponse.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                final HeaderElement he = it.nextElement();
                final String param = he.getName();
                final String value = he.getValue();
                if ((value != null) && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            final HttpHost target = (HttpHost) myContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            if ("localhost".equalsIgnoreCase(target.getHostName())) {
                return 10 * 1000;
            } else {
                return 5 * 1000;
            }
        }
    };
    client = HttpClients.custom().setKeepAliveStrategy(myStrategy).setConnectionManager(poolingConnManager).build();
    client.execute(get1);
    client.execute(get2);
}
Also used : BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) HeaderElementIterator(org.apache.http.HeaderElementIterator) ConnectionKeepAliveStrategy(org.apache.http.conn.ConnectionKeepAliveStrategy) HeaderElement(org.apache.http.HeaderElement) HttpHost(org.apache.http.HttpHost) HttpContext(org.apache.http.protocol.HttpContext) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicHeaderElementIterator(org.apache.http.message.BasicHeaderElementIterator) Test(org.junit.Test)

Example 27 with HttpContext

use of org.apache.http.protocol.HttpContext in project tutorials by eugenp.

the class HttpClientCookieLiveTest method whenSettingCookiesOnTheRequest_thenCookieSentCorrectly.

@Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    instance = HttpClientBuilder.create().build();
    final HttpGet request = new HttpGet("http://www.github.com");
    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
    response = instance.execute(request, localContext);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
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) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) Test(org.junit.Test)

Example 28 with HttpContext

use of org.apache.http.protocol.HttpContext in project connect-sdk-java by Ingenico-ePayments.

the class DefaultConnection method createHttpClient.

private CloseableHttpClient createHttpClient(ProxyConfiguration proxyConfiguration) {
    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager);
    HttpRoutePlanner routePlanner;
    CredentialsProvider credentialsProvider;
    if (proxyConfiguration != null) {
        HttpHost proxy = new HttpHost(proxyConfiguration.getHost(), proxyConfiguration.getPort(), proxyConfiguration.getScheme());
        routePlanner = new DefaultProxyRoutePlanner(proxy, DefaultSchemePortResolver.INSTANCE);
        credentialsProvider = new BasicCredentialsProvider();
        if (proxyConfiguration.getUsername() != null) {
            AuthScope authscope = new AuthScope(proxyConfiguration.getHost(), proxyConfiguration.getPort());
            final Credentials credentials = new UsernamePasswordCredentials(proxyConfiguration.getUsername(), proxyConfiguration.getPassword());
            credentialsProvider.setCredentials(authscope, credentials);
            // enable preemptive authentication
            HttpRequestInterceptor proxyAuthenticationInterceptor = new HttpRequestInterceptor() {

                @Override
                public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                    Header header = request.getFirstHeader(AUTH.PROXY_AUTH_RESP);
                    if (header == null) {
                        header = new BasicScheme((Charset) null).authenticate(credentials, request, context);
                        if (!AUTH.PROXY_AUTH_RESP.equals(header.getName())) {
                            header = new BasicHeader(AUTH.PROXY_AUTH_RESP, header.getValue());
                        }
                        request.setHeader(header);
                    }
                }
            };
            builder = builder.addInterceptorLast(proxyAuthenticationInterceptor);
        }
    } else {
        // add support for system properties
        routePlanner = new SystemDefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault());
        credentialsProvider = new SystemDefaultCredentialsProvider();
    }
    // add logging - last for requests, first for responses
    LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
    builder = builder.addInterceptorLast((HttpRequestInterceptor) loggingInterceptor);
    builder = builder.addInterceptorFirst((HttpResponseInterceptor) loggingInterceptor);
    return builder.setRoutePlanner(routePlanner).setDefaultCredentialsProvider(credentialsProvider).build();
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) DefaultProxyRoutePlanner(org.apache.http.impl.conn.DefaultProxyRoutePlanner) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SystemDefaultCredentialsProvider(org.apache.http.impl.client.SystemDefaultCredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) ResponseHeader(com.ingenico.connect.gateway.sdk.java.ResponseHeader) RequestHeader(com.ingenico.connect.gateway.sdk.java.RequestHeader) BasicHeader(org.apache.http.message.BasicHeader) HttpRoutePlanner(org.apache.http.conn.routing.HttpRoutePlanner) HttpHost(org.apache.http.HttpHost) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) AuthScope(org.apache.http.auth.AuthScope) HttpResponseInterceptor(org.apache.http.HttpResponseInterceptor) SystemDefaultCredentialsProvider(org.apache.http.impl.client.SystemDefaultCredentialsProvider) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) BasicHeader(org.apache.http.message.BasicHeader) SystemDefaultRoutePlanner(org.apache.http.impl.conn.SystemDefaultRoutePlanner)

Example 29 with HttpContext

use of org.apache.http.protocol.HttpContext in project ecf by eclipse.

the class SNIAwareHttpClient method createClientConnectionManager.

@Override
protected ClientConnectionManager createClientConnectionManager() {
    SSLSocketFactory factory = new SSLSocketFactory(SSLContexts.createSystemDefault(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER) {

        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException, ConnectTimeoutException {
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=478655
            if (socket instanceof SSLSocket) {
                try {
                    final Method mSetHost = socket.getClass().getMethod("setHost", String.class);
                    mSetHost.setAccessible(true);
                    mSetHost.invoke(socket, host.getHostName());
                } catch (NoSuchMethodException ex) {
                } catch (IllegalAccessException ex) {
                } catch (InvocationTargetException ex) {
                } catch (RuntimeException ex) {
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    final SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, factory));
    return new BasicClientConnectionManager(registry);
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) HttpContext(org.apache.http.protocol.HttpContext) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpHost(org.apache.http.HttpHost) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 30 with HttpContext

use of org.apache.http.protocol.HttpContext in project coastal-hazards by USGS-CIDA.

the class HttpComponentsWFSClient method getFeatureCollection.

@Override
public SimpleFeatureCollection getFeatureCollection(String typeName, Filter filter) throws IOException {
    SimpleFeatureCollection collection = null;
    String filterXml = null;
    InputStream is = null;
    OutputStream os = null;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (filter != null) {
        try {
            FilterTransformer transformer = new FilterTransformer();
            transformer.setOmitXMLDeclaration(true);
            transformer.setNamespaceDeclarationEnabled(false);
            filterXml = "<ogc:Filter>" + transformer.transform(filter) + "</ogc:Filter>";
        } catch (TransformerException ex) {
            throw new RuntimeException("Specified filter cannot be transformed", ex);
        }
    } else {
        filterXml = "";
    }
    try {
        HttpPost post = new HttpPost(wfsEndpoint);
        StringEntity stringEntity = new StringEntity(fillInTemplate(typeName, filterXml), ContentType.APPLICATION_XML);
        post.setEntity(stringEntity);
        HttpContext localContext = new BasicHttpContext();
        httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
        HttpResponse methodResponse = httpClient.execute(post, localContext);
        if (methodResponse.getStatusLine().getStatusCode() != 200) {
            throw new IOException(methodResponse.getStatusLine().getReasonPhrase());
        }
        is = methodResponse.getEntity().getContent();
        os = new FileOutputStream(tmpWfsFile);
        IOUtils.copy(is, os);
    } finally {
        if (httpClient.getConnectionManager() != null) {
            httpClient.getConnectionManager().closeExpiredConnections();
        }
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
    collection = new GMLStreamingFeatureCollection(tmpWfsFile);
    return collection;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) StringEntity(org.apache.http.entity.StringEntity) NoConnectionReuseStrategy(org.apache.http.impl.NoConnectionReuseStrategy) GMLStreamingFeatureCollection(gov.usgs.cida.gml.GMLStreamingFeatureCollection) FileOutputStream(java.io.FileOutputStream) FilterTransformer(org.geotools.filter.FilterTransformer) TransformerException(javax.xml.transform.TransformerException)

Aggregations

HttpContext (org.apache.http.protocol.HttpContext)187 HttpResponse (org.apache.http.HttpResponse)81 IOException (java.io.IOException)74 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)59 HttpRequest (org.apache.http.HttpRequest)57 HttpException (org.apache.http.HttpException)34 HttpGet (org.apache.http.client.methods.HttpGet)31 Test (org.junit.Test)30 HttpHost (org.apache.http.HttpHost)28 HttpPost (org.apache.http.client.methods.HttpPost)28 StringEntity (org.apache.http.entity.StringEntity)23 ArrayList (java.util.ArrayList)22 Header (org.apache.http.Header)22 MessageContext (org.apache.axis2.context.MessageContext)19 NameValuePair (org.apache.http.NameValuePair)18 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)18 ProtocolException (org.apache.http.ProtocolException)17 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)17 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)17 URI (java.net.URI)16